home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 2000 August: Tool Chest / Dev.CD Aug 00 TC Disk 2.toast / pc / sample code / sound / soundapp / soundapp.c next >
Encoding:
Text File  |  2000-06-23  |  170.5 KB  |  4,667 lines

  1. /*
  2.     File:        SoundApp.c
  3.  
  4.     Contains:    1.04: This was an update to support the Utilities Unit that MacDTS
  5. developed.  Some of it was routines formally created for SoundApp,
  6. with additional ones coming from other sources.  This helps to reduce
  7. the "destractive" code from the samples and makes them easier to maintain.
  8.  
  9. 1.1:     • This is the "new" SoundApp which adds some new features.
  10.         • Some knowledge of the new Sound Manager is present
  11.           in areas that were work-arounds for old Sound Manager bugs
  12.         • Recording of sounds is now possible with the Sound Input Manager
  13.         • The document window will keep the Record button hidden if
  14.           the Sound Inpute Manager is not available for recording,
  15.           otherwise it will expand the window size to show this button.
  16.         • Supports copy and pasting of sound resources
  17.         • Conversion to MPW 3.2 was established (with some amount of pain)
  18.         • SoundApp now has its own documents
  19.         • Supports launching by open documents from Finder
  20.         • Added color icons for the System 7.0 desktop
  21.         • Added the new Sound Manager error strings
  22.         • DoErrorSound tests for safe beeps
  23.         • Made Apple Legal happy by getting rid of the xxxxCmd
  24.           and changed it to the freqDurationCmd.  Also got rid of
  25.           any other use of the work "xxxx" in a musical context
  26.  
  27. 1.2:    • Translated into C, some clean up along the way
  28.         • Using universal headers
  29.         • Gave up on the DTS utilities code, everything is self-contained
  30.  
  31. Formatting was done with FONT = Courier, SIZE = 10, TABS = 4
  32.  
  33. many thanks to: Bo3b Johnson, Mark Bennett, Andy Shebanow, Keith
  34. Rollin, Chris Derossi, Pete Helme, Darin Adler, and my co-workers that
  35. sat near me while I was making lots of noise testing this application.
  36.  
  37. To the reader,
  38.  
  39. SoundApp.p is a sample application source file for demonstrating
  40. the Sound Manager.  It requires the use of the SoundUnit to handle
  41. all of the sound routines.  This portion of the source code handles the
  42. application’s management of memory, errors, user interface, etc..
  43. The read me notes are here in the source code because people tend to
  44. not read them otherwise.
  45.  
  46. SoundApp is a demonstration of the Sound Manager released in System
  47. 6.0.x.  SoundApp is also a example of how to write a Macintosh
  48. application that performs good user interface and proper error
  49. handling.  Believe it or not, but the Sound Manager portion was the
  50. easiest part for me to write.  It was all the user interface and error
  51. handling that was the most difficult.  One thing became very clear to
  52. me in the course of writing this application.  The following axiom is
  53. one of the few great truths in the universe.
  54.  
  55. If you write a Macintosh application without MacApp, you’re working
  56. too hard.
  57.  
  58. Throughout the development of SoundApp I would run into typical
  59. situations that make programming a Macintosh too hard.  When this
  60. happened I asked myself “what would MacApp do?” and that was followed
  61. by the thought “then why am I writing code that is already out there
  62. for me to use?”  I started out intending on writing a very simple
  63. application that anyone could read, and understand the Sound Manager.
  64. I felt this meant not requiring the person to read Object Oriented
  65. Pascal.  I accomplished part of my goal.  People should be able to
  66. learn how to use the Sound Manager (in its present condition), but it
  67. didn’t turn out to be such a simple application as I had hoped for.
  68.  
  69. I have put a large amount of comments into the code.  This is
  70. something I’m really picky about.  People do not comment their code
  71. enough.  Each procedure has a paragraph that should explain what to
  72. expect that routine to do, and how it goes about doing it.  There are
  73. some bigger issues that I will put into the release notes below.
  74. There are some things that make the Macintosh harder to develop for
  75. than it should be.  Simple things should be simple.  Too many things
  76. on the Mac that should be simple are not.  Maybe someday these things
  77. will be fixed.
  78.  
  79. • GetFontInfo requires a port set to the font in question.  If I
  80. wanted to find the height of the System Font, I had to first set the
  81. current port to the WindowMgr.  I could have used my own window, but
  82. what if I needed the font info before I had a window available?
  83. • The toolbox blows chunks when your heap gets “too low.”  I believe
  84. this magical number is between 32k and zero.  The odds of blowing
  85. chunks increase logarithmically as one approaches 0 free bytes.
  86. • The Dialog Manager is not a free lunch and in fact will cost you
  87. plenty.
  88. • There’s no safe way to determine how much memory opening a
  89. resource file will take away from your heap.
  90. • There’s no way to determine how safe it is opening a resource that
  91. could be shared by other applications, especially on a local volume.
  92. • The Resource Manager doesn’t always set ResErr.
  93. • The Sound Manager returns even less errors.
  94. • The List Manager returns no errors.
  95. • Writing a staggering routine for new windows encompasses a number
  96. of difficulties.  How does one find the height of a window’s title
  97. region before the window is visible?
  98.  
  99. Am I just a complainer?  Do I have a bad attitude?  Probably, but
  100. I’m just trying to point out the above areas make the Mac programming
  101. experience difficult.  These are areas that get developers into
  102. trouble.  These areas need a sign in front of them that says,
  103. “Danger!”  These are areas that developers get into and then write to
  104. MacDTS for help.
  105.  
  106. Notation Conventions
  107. --------------------
  108. All global variables begin with a lower case “g”.
  109. All constants begin with “k” except for those noted here.
  110. Resource IDs begin with “r”.
  111. Menu IDs being with “m” and items with an “i”.
  112. Resource strings begin with “s”.
  113.  
  114. Human Interface
  115. ---------------
  116. This is the most important and about the most difficult aspect of
  117. programming on the Macintosh.  In the development of SoundApp I gave much
  118. thought to the human interface issues.  In fact, in talking with the Human
  119. Interface Group additions to the existing guidelines were made.  The
  120. method of window stacking used here was a new one.  This was documented in
  121. a Human Interface Tech Note.  I even made one compromise (hard to
  122. believe!) suggested by the Human Interface Group.  I originally had the
  123. buttons and the list in my choice of font and size.  They felt that
  124. buttons should be in the System font and the list should also be the same.
  125. I liked my font choice better, but the group had a point that I really
  126. couldn’t argue with.  That was, “If there isn’t a compelling reason to
  127. change something standard, then don’t change it.”  Buttons on a Macintosh
  128. typically appear in the System font.  Changing the font, just because I
  129. wanted to, was considered gratuitous.  Standard File is in the System font
  130. and it also contains a list and buttons.  Since my window are very similar
  131. to that dialog, I’m using the System Font.
  132.  
  133. SoundApp is never modal unless an error occurs and I need to show and
  134. alert.  Controls are inactivated for inactive windows.  The default button
  135. is given the proper outline, and this outline disappears when the window
  136. is deactivated.  Keyboard equivalents for the buttons cause the button to
  137. appear as if it had been clicked in.  The check box in the Standard File
  138. dialog remembers the user’s last setting.  The about box is only
  139. semi-modal.  It will allow the user access to switch to another application.
  140. The status window under some circumstances was found to disappear too quickly,
  141. so a built in delay was added.  Windows are centered or stacked according
  142. to the Human Interface Guidelines.  The sound level isn’t adjusted by the
  143. application, and instead the users is informed of the current level and
  144. told how it can be adjusted.
  145.  
  146. The About box
  147. -------------
  148. It’s rad.  Has a color icon, shows the 'vers' resource, goes Moof!™.  It
  149. also demonstrates how to handle a modal window without the Dialog Manager.
  150. This technique can be use for any window, including dialog windows.  The
  151. dialog’s update routine would call UpdtDialog.  The really new point to
  152. notice is this window is modal but ONLY within the application’s layer.
  153. While running under MultiFinder, the user can switch to other
  154. applications.  While the About window is present, it is the only window
  155. belonging to the application that accepts user actions.
  156.  
  157. Memory Management
  158. ----------------
  159. This has to be the most difficult portion of a Mac application to
  160. write.  This along with the user interface.  I spent too many nights
  161. chasing down crashes while running the application under low memory.
  162. I found unpleasant surprises while doing this.  The Sound Manager
  163. doesn’t check for NIL pointers.  OpenResFile may take large portions
  164. of my heap away.  The toolbox seems to need at least 32k of free space
  165. in the heap of my Mac II running color.
  166.  
  167. I wrote a simple grow zone procedure that will dump a reserve memory
  168. block.  This is only considered for use in an emergency.  I never rely
  169. on using it directly.  If the reserve has been released, I will not
  170. continue an operation such as playing a sound or showing the status
  171. window until it is regained.  Grow zones should not be considered a
  172. solution to memory management.  They can be used to augment your
  173. overall memory management scheme.
  174.  
  175. Error Checking
  176. --------------
  177. Lots and lots and lots of it.  I could even do more.  Programmers
  178. need to do more of this.  The Sound Manager will crash when
  179. encountering a NIL pointer.  My application should never crash.  If
  180. you can find a way to crash this application, then I want to hear
  181. about it.  Using a bogus 'snd ' resources doesn’t count and I’ve found
  182. many of those.  Writing proper error checking into the code during
  183. development really helped.  Always handle errors, and pass along the
  184. error.  I will let the first error encountered to be passed all the
  185. way up to the caller and eventually my error dialog will show up for
  186. the user.
  187.  
  188. SetPort Strategy
  189. ----------------
  190. Any routine that needs to use Quickdraw will set the port.  I do not
  191. believe that it should also be responsible for restoring the port back
  192. to what it may have been before the routine was called.  So, you’ll
  193. find there is an absence of the GetPort, SetPort, do my thing, and
  194. then SetPort again.  Instead I SetPort and do my thing.  The Mac often
  195. is setting the port unnecessarily.
  196.  
  197. Strings
  198. -------
  199. All of my strings are resources.  There are no strings that appear
  200. within the code.  This helps memory management and allows me to adjust
  201. the application to international systems without compiling any code.
  202. I could simply use ResEdit, or some other tool, to localize this
  203. application.  I find it is just as easy to run Rez again than
  204. attempting to use ResEdit.  Besides, after editing with ResEdit I want
  205. the source for that and would have to run DeRez which isn’t nearly as
  206. clean as my original source files.
  207.  
  208. Window Stacking
  209. ---------------
  210. I hate applications that will open a new document that covers up an
  211. existing document, unless the new document covers the entire screen.
  212. So, my application’s documents have a small window size.  I wanted to
  213. open new windows that would not cover up older ones.  This is nice for
  214. the user, since they will not have to move windows just to get at
  215. other documents.  ResEdit will stagger new windows off of the
  216. frontmost window but I find that this isn’t the best approach.  It
  217. will still cover up other windows and I also don’t like windows that
  218. will open half way between two monitors.  I wanted a better approach:
  219. one that would always stagger new windows and not cover up older ones.
  220.  
  221. When I want to center a window, I need to know its entire rectangle
  222. size.  The rub is that I cannot determine its size until I show it
  223. because I only know about the window’s boundsRect.  This does not
  224. include the area that contains the title bar.  That’s the strucRgn,
  225. which is an empty region for an invisible window.  I could do what
  226. MacApp does, but if I have to do another thing that MacApp already
  227. does I’ll give up and stick with MacApp.  I ended up writing a routine
  228. that takes a guess at the height of the window’s title bar.  This is
  229. another thing that was harder than it should have been.
  230.  
  231. Dialog Manager (and some of the reasons I don’t like it)
  232. --------------------------------------------------------
  233. My first approach was to use modeless dialogs for document windows,
  234. thinking that I could write an application that would demonstrate how to
  235. deal with them and all of their idiosyncrasies.  Not long into the
  236. development cycle it became obvious to me that I was fighting something
  237. that contained more disadvantages than advantages.  I removed all the
  238. dialog code and only used standard windows and controls the old fashion
  239. way.  In the case of the About window, which is semi-modal, I have a test
  240. that will return TRUE for a window that should be treated as modal.  This
  241. allows my window to be handled by my standard event handlers and I don’t
  242. have to write dialog filters.  There are some things that do not get
  243. handled properly while calling ModalDialog.  ModalDialog ignores disk
  244. insert events.  The activate or update events do not get handled for
  245. background windows.  Using a modeless dialog fails with MultiFinder if
  246. switching takes place while the dialog is the frontmost window.  The
  247. problem is that DialogSelect ignores and removes the suspend/resume event.
  248. Another advantage to all this is that drawing was much faster.
  249.  
  250. As an example of some of the problems with ModalDialog and the activate
  251. event.  Try this with the Finder.  Open a window and choose “View by name.”
  252. Then select a few names with the shift key and resize the window so the
  253. vertical scroll bar is visible.  Move this window to one edge of the
  254. screen or a second monitor.  Now choose “Set Startup.”  This is a modal
  255. dialog.  If you look at the Finder window with the selected files, you’ll
  256. notice that the scrollbar and the text are still highlited.  This is not
  257. the proper user interface.  This is because the deactivate routines are
  258. not called while in ModalDialog.  You can even find this problem with
  259. SoundApp.  On deactivate events I will change my controls to the inactive
  260. state.  If you place the buttons to the side of the screen and then bring
  261. up the standard file dialog, you’ll notice that the buttons don’t change
  262. properly.  ModalDialog also prevents the application from updating
  263. background windows too.  To solve this a dialog filter procedure is
  264. required.  In most cases, this filter would be as complex and the event
  265. loop.  It would also make it necessary to call your event routines from
  266. outside of the normal event loop.  All on this isn’t worth the effort.
  267.  
  268. You can see how this does not happen while using this application’s
  269. About window.  Select an item in the document window and choose “Play
  270. Melody.”  This will leave the status window on screen so that you can
  271. drag it to cover the document window.  Now select “About SoundApp” to
  272. bring up the about window.  This causes the status window to close,
  273. which uncovers the document window leaving an invalid area.  The
  274. document window gets an activate event, then the About window appears.
  275. Then the document window is properly deactivated and updated.  Yeah,
  276. just like it should happen.
  277.  
  278. So, the tradeoff was that I didn’t have to work around all the
  279. strange things the Dialog Manager does such as running a secondary
  280. event loop, and requiring me to have userItems or filterProcs.  This
  281. made the code smaller, more readable, and faster.  I think I will
  282. avoid the Dialog Manger from now one unless I’m using a very simple
  283. dialog.  The about window of this application proved too much for the
  284. Dialog Manager.
  285.  
  286. One thing dialogs are good for is running ResEdit and laying out the
  287. dialog.  To help position controls, I used a DLOG resource of the same
  288. size as my WIND resource.  The DITL of this dialog contains the
  289. positions I wanted for my CNTL resources.  This helped me to look at
  290. where I could expect my buttons to show up.  This is one of the main
  291. reasons people think they need the Dialog Manager, because ResEdit
  292. makes it easy to build dialogs.  ResEdit alone has contributed to
  293. nearly all of the Dialog Manager abuse in the world today.
  294.  
  295. I used a Rect resource for positioning the list rectangle of the
  296. document windows.  These windows look very much like a modeless
  297. dialog.  (They used to be, but that presented to many problems.)  The
  298. About window is also a standard window, but shown modally.  Just like
  299. ModalDialog, but my modal window does allow switching under
  300. MultiFinder.  You can change the window to a dBoxProc and then
  301. MultiFinder will not switch while this is the active window.  To help
  302. with the layout of the about window, I position the text within it
  303. based on the size of the window.  The status window does this too.
  304. These two things, the Rect resource and text based on the size of the
  305. window, help when changing the text.  If the new text doesn’t fit,
  306. then resize the window’s resource.  I used some trick with Rez to help
  307. layout my window contents.  Refer to the SoundApp.r sources.
  308.  
  309. I’ve read and understood Tech Note 203, and have learned how to
  310. apply it.  Bo3b Johnson is a smart guy, and developers should trust
  311. his opinions.
  312.  
  313. List Manager
  314. ------------
  315. It’s very easy to be tempted by this part of the toolbox, along with
  316. the Dialog Manager.  The List Manager is a slow beast at times.  It
  317. also has some problems with “doing the right thing.”  I’ve found that
  318. the list will not be updated properly when the user clicks in a cell
  319. that is out of bounds.  LClick will return TRUE with a cell that
  320. doesn’t exists.  LActivate will erase the scrollbars instead of
  321. highlighting the properly.  Finally, the List Manager does not return
  322. errors.  How would a person know if LSetCell worked?
  323.  
  324. I’ve read and understood Tech Note 203, and have learned how to
  325. apply it.
  326.  
  327. Resource Manager
  328. ----------------
  329. I test all the handles being returned from the Resource Manager
  330. before using them, and if I get a NIL then I look at ResError.
  331. ResError sometimes lies and returns noErr and a NIL handle.  ResError
  332. is usually good for getting an error code AFTER you’ve already found
  333. an error.
  334.  
  335. Opening a resource file that is already open by another application
  336. is dangerous.  The Resource Manager will not tell you when you’ve done
  337. this.  There needs to be a OpenRFPerm that will return permission
  338. errors such as resFileBusyErr.  Refer to Tech Note 185.
  339.  
  340. When I or the Toolbox needs to get at one of my resources,
  341. CurResFile must be set to my application.  Also, look out for one
  342. particularly nasty situation when switching resource files.   If the
  343. segment loader goes for a CODE segment, it better be from our resource
  344. file!  The idea here is, in case you didn’t get it already, always
  345. have the current resource file be set to the application.  If a
  346. resource is needed from another file, switch momentarily to get the
  347. resource and immediately restore the current resource file to the
  348. application.  I take an added measure of defense and whenever I need a
  349. resource I use the Get1Resource calls.  These will only search the
  350. current resource file.
  351.  
  352. Strategies For Sound
  353. --------------------
  354. All of the Sound Manager code is contained in the SoundUnit.p.  This
  355. code was written to be general purpose, providing useful routines for
  356. other applications.  Lots of error checking is performed.  I’ve also
  357. extended the support for SndPlay and made it really asynchronous.
  358. I’ve demonstrated most of the abilities the present Sound Manager has
  359. to offer.  I will have to revise the SoundAppUnit to include any new
  360. features (e.g., multi channel support) when the next Sound Manager is
  361. released.
  362.  
  363. I allocate my own memory to be used as sound channels.  I allocate
  364. these pointers early in the application’s startup time to avoid memory
  365. fragmentation.  These channels are of the standard size (holding 128
  366. commands) but I’ve extended the structure to include my own
  367. information.  When I create a new sound channel, I pass it a pointer
  368. to this memory.  This will link in the 'snth' resource and hardware to
  369. my channel.  When I dispose of the channel, the Sound Manager will
  370. purge this resource and disconnect me from the hardware.  When adding
  371. the 'snth' resource, the Sound Manager will allocate a pointer into
  372. the application’s heap instead of the system’s.  This is a modifier
  373. stub used by the 'snth'.  This could cause some problems with memory
  374. management.  I create and dispose of all my channels as soon as
  375. possible, and this doesn’t cause me problems.
  376.  
  377. I keep track of which document is playing a sound, along with a
  378. global of when the application is playing sound.  I needed to keep
  379. track of which document is playing because if the user disposes of
  380. that document, I will have to stop playing the sound contained in it
  381. since the user wants to dispose of that data.  I keep track of when
  382. the application is playing sound in a global.  This is only used by
  383. the routine that calculates the sleep time for WaitNextEvent.
  384.  
  385. I came up with a pretty sick music notational system using Rez.
  386. Refer to the notes in the SoundAppSnds.r file.  If you’ve just
  387. finished a meal, wait four hours before reading.
  388.  
  389. The SoundUnit handles all of the Sound Manager code entirely.  This
  390. eliminates any and all references to the Sound Manager from the
  391. application.  The SoundUnit will return any error encountered while
  392. calling the Sound Manager, and does some extra error checking the
  393. Sound Manager doesn’t do.
  394.  
  395. The portion of the application that uses the wave table synthesizer
  396. is more complex than the other two.  I wanted to include an example
  397. channel modifier for use in the wave table channels.  This would have
  398. been a transpositional modifier that would take a given freqDurationCmd and
  399. transpose it by some amount.  This would be nice for the routine that
  400. plays a scale, by allowing the other three channels to be playing the
  401. same scale but at a different interval.  Unfortunately, I found that
  402. the Sound Manager has bugs using a modifier, at least with the wave
  403. table synths, and could not use them.
  404.  
  405. I’ve created a few wave table sounds and keep them in a 'snd '
  406. resource.  This allows me to change the sound of the wave table
  407. channels and not change any of the code.  Creating wave table data is
  408. complicated.  The example sounds I’ve included are samples I’ve taken
  409. from various sources.  I’ve cleaned them up quit a bit.  This was to
  410. set loop points, try and reduce clicks, correct the sample rates, and
  411. base frequencies.  This is also a complicated task.  Maybe I should document
  412. these techniques.
  413.  
  414.     Written by: Jim Reekes    
  415.  
  416.     Copyright:    Copyright © 1994-1999 by Apple Computer, Inc., All Rights Reserved.
  417.  
  418.                 You may incorporate this Apple sample source code into your program(s) without
  419.                 restriction. This Apple sample source code has been provided "AS IS" and the
  420.                 responsibility for its operation is yours. You are not permitted to redistribute
  421.                 this Apple sample source code as "Apple sample source code" after having made
  422.                 changes. If you're going to re-distribute the source, we require that you make
  423.                 it clear in the source that the code was descended from Apple sample source
  424.                 code, but that you've made changes.
  425.  
  426.     Change History (most recent first):
  427.                 7/29/1999    Karl Groethe    Updated for Metrowerks Codewarror Pro 2.1
  428.                 
  429.  
  430. */
  431. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  432. // global defines
  433.  
  434. // All of this code is for System 7 and later
  435. #define SystemSevenOrLater 1
  436.  
  437. // I don't use any obsolete stuff in the interfaces, and you shouldn't either.
  438. // You also need to worry about names because the Code Fragment Manager binds
  439. // system calls by name. Read the comments in ConditionalMacros.h
  440. #define OLDROUTINENAMES 0
  441.  
  442.  
  443. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  444. // includes
  445. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  446. #include <FixMath.h>
  447. #include <AppleEvents.h>
  448. #include <Controls.h>
  449. #include <Devices.h>
  450. #include <DiskInit.h>
  451. #include <Dialogs.h>
  452. #include <Errors.h>
  453. #include <Events.h>
  454. #include <Files.h>
  455. #include <Icons.h>
  456. #include <Gestalt.h>
  457. #include <Lists.h>
  458. #include <LowMem.h>
  459. #include <Menus.h>
  460. #include <Memory.h>
  461. #include <QuickDraw.h>
  462. #include <Resources.h>
  463. #include <Scrap.h>
  464. #include <Script.h>
  465. #include <SegLoad.h>
  466. #include <StandardFile.h>
  467. #include <TextUtils.h>
  468. #include <ToolUtils.h>
  469. #include <Traps.h>
  470. #include <Types.h>
  471. #include <Windows.h>
  472.  
  473. #include <limits.h>
  474. #include <string.h>
  475.  
  476. #include <Sound.h>
  477. #include <SoundInput.h>
  478. #include "SoundUnit.h"
  479.  
  480. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  481. // constants
  482. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  483.  
  484. enum {
  485.     kOSTrapBit                = (1<<11),    /* bit 11 is the OS Trap bit */
  486.     kTrapNumberMask            = 0x07FF,    /* bits used by the A-Trap mechanism */
  487.  
  488.     kPollingSleepTime        = 60,        //MultiFinder’s sleep while sound is playing
  489.  
  490.     kNumberOfMasters        = 3,        //number of master pointer blocks we expect
  491.     kSizeOfReserve            = (unsigned long)32 * 1024, //size of reserve memory for grow zone proc
  492.     kMinSpace                = (unsigned long)32 * 1024, //minimum available memory I allow in heap
  493.     kMemForSndDoc            = 20 * 1024, //minimal amount of memory needed by document
  494.  
  495.     rAppSignature            = 'SAPP',    //applicaiton’s OS signature
  496.     rSndAppDocType            = 'sDoc',    //document's file type
  497.  
  498.     kScrollbarAdjust        = 16-1,        //the width of the scrollbar in the list
  499.     kListFrameInset            = -1,        //inset rectangle adjustment for list frame
  500.     kStadardWhiteSpacing    = 13,        //inset rectangle adjustment for dialog items
  501.  
  502.     kRecordTop                = 40,        //40,50 is topLeft for SndRecord dialog
  503.     kRecordLeft                = 50,        //40,50 is topLeft for SndRecord dialog
  504.  
  505.     kHiliteControlSelect    = 1,        //select the control
  506.     kHiliteControlDeselect    = 0,        //deselect the control
  507.     kCntlOn                    = 1,        //control’s value when truned on
  508.     kCntlOff                = 0,        //control’s value when truned off
  509.  
  510.     kWindowPosStartPt        = 2,        //offset from the topLeft of the screen
  511.     kWindowPosStaggerH        = 16,        //staggering amounts for new windows
  512.     kWindowPosStaggerV        = 3,        //not including the window’s title height
  513.  
  514.     kMinWindowTitleHeight    = 19,
  515.     kButtonFrameSize        = 3,        //button’s frame pen size
  516.     kButtonFrameInset        = -4,        //inset rectangle adjustment around button
  517.     kButtonSizeH            = 17,        //standard height of buttons
  518.     kDafaultButSizeH        = kButtonSizeH - kButtonFrameInset - kButtonFrameInset
  519. };
  520.  
  521. //refer to the SoundApp.r file for the explaination about these numbers
  522. enum {
  523.     kNumOfButtons            = 6,        //the number of buttons in the window
  524.     kSndButtonSizeW            = 100,        //SizeW of buttons in document window
  525.     kSndButtonSizeH            = 22,        //heigth of buttons in document window
  526.     kSoundWindowSizeH        = ((kNumOfButtons * (kStadardWhiteSpacing + kSndButtonSizeH))
  527.                                 + kStadardWhiteSpacing),
  528.     kSoundWindowSizeW        = 296,
  529.  
  530.     //standard position for icons in alerts
  531.     kIconWidthOrHeight        = 32,
  532.     kStdAlertIconTop        = kStadardWhiteSpacing,
  533.     kStdAlertIconLeft        = 23,
  534.     kStdAlertIconBottom        = kStdAlertIconTop + kIconWidthOrHeight,
  535.     kStdAlertIconRight        = kStdAlertIconLeft + kIconWidthOrHeight,
  536.  
  537.     kFSAsynch                = true,        //asynchronous File Manager call
  538.  
  539.     kEnterKey                = '\3',     //the keys I’m looking for
  540. #ifdef applec
  541.     kReturnKey                = '\n',        //MPW C is wrong, the return key is "\r" not "\n"
  542. #else
  543.     kReturnKey                = '\r',
  544. #endif
  545.     kEscape                    = '\33',
  546.     kUpArrow                = '\36',
  547.     kDownArrow                = '\37',
  548.     kPeriod                    = '.',
  549.     kBackspace                = '\b',
  550.  
  551. //This bit set in the ioFlAttrib field if the file’s resource fork is open.
  552.     kResForkOpenBit            = (1 << 2),
  553.  
  554. //For the delay time when flashing the menubar and highlighting a button.
  555.     kDelayTime                = 8,        //8/60ths of a second
  556.  
  557. //The minimal number of ticks the ShowWindow needs to be visible.
  558.     kShowTimeDelay            = 20,
  559.  
  560. //BUG NOTE: timbreCmd value of 255 on the Mac Plus/SE will cause a crash Sound Manager 1
  561.     kSquareWave                = 240,         //square wave for squareWaveSynth
  562.     kSineWave                = 0,        //sine wave for the squareWaveSynth
  563.     kPreferredTimbre        = 190,        //my preferred timbre for the squareWaveSynth
  564.  
  565. //Application snd resources must be higher than this number.
  566.     kSystemSndRange            = 8191        //This is the highest snd id reserved by Apple.
  567. };
  568.  
  569. //The following constants are the resource IDs.
  570. enum {
  571.     rMenuBar                = 1000,        //application’s menu bar
  572.  
  573.     rExitAlert                = 1000,        //emergency exit user alert
  574.     rUserAlert                = 1001,        //error message user alert
  575.     rSoundVolAlert            = 1002,        //sound is set low alert
  576.     rSaveAlert                = 1003,        //save changes? dialog
  577.  
  578.     rGetNameDLOG            = 2000,        //get a name for the sound dialog
  579.     rNameItem                = 3,        //edit text item in rGetNameDLOG
  580.     rUserItem                = 5,        //user item to help draw default outline
  581.  
  582.     rCustomGetFileDLOG        = 2001,        //dialog template for CustomGetFile
  583.     rSndOnlyCheckBox        = 10        //dialog item number in CustomGetFile
  584. };
  585.  
  586. /*
  587. These are the window IDs used in the applications.  Each one must be unique,
  588. since they are used to identify which window the event took place in.
  589. */
  590. enum{
  591.     rAboutWindow            = 1000,        //about window
  592.     rStatusWindow            = 1001,        //sound status window
  593.     rSoundWindow            = 1002,        //sound document window
  594.  
  595.     rListRectID                = 1000,        //resource containing size of list rectangle
  596.  
  597.     rCancelCntl                = 1000,        //stop button ID for the status window
  598.     rPlaySndCntl            = 1001,        //sound button IDs for the sound document window
  599.     rHyperPlayCntl            = 1002,
  600.     rPlayScaleCntl            = 1003,
  601.     rMelodyCntl                = 1004,
  602.     rStopCntl                = 1005,
  603.     rRecordCntl                = 1006,
  604.     rAboutOkCntl            = 1007,
  605.     rUntitled                = 1000,        //string ID for untitled resources
  606.     rAboutText                = 1001,        //string ID for text appearing in about window
  607.     rPutFileMsg                = 1002,        //string for text appearing in SFPutFile dialog
  608.     rMoofIcon                = 1000,        //resource ID for ICON of application
  609.     rAppPict                = 1000,        //resource ID of picture shown in about window
  610.     rSndCursor                = 1000        //cursor resource for our documents
  611. };
  612.  
  613. /*
  614. The following are the snd resource IDs contained in the application,
  615. which start at ID 9000.  IDs 0 - 8191 are reserved for Apple.
  616. */
  617. enum {
  618.     rMoofSound                = 9000,        //snd for the about window
  619.     rScaleSnd                = 9001,        //snd containing a scale
  620.     rMelodyPart1            = 9002,        //snd containing a melody
  621.     rMelodyPart2            = 9003,        //snd containing the harmony
  622.     rMelodyPart3            = 9004,        //snd containing the harmony
  623.     rMelodyPart4            = 9005,        //snd containing the harmony
  624.     rWaveHarmony            = 9006,        //snd containing waveTable for harmony
  625.     rWaveMelody                = 9007,        //snd containing waveTable for melody
  626.     rCounterPt1                = 9008,        //snd containing soprano part of counter point
  627.     rCounterPt2                = 9009,        //snd containing alto part of counter point
  628.     rCounterPt3                = 9010,        //snd containing tenor part of counter point
  629.     rCounterPt4                = 9011,        //snd containing bass part of counter point
  630.     rSopranoVox                = 9012,        //snd containing waveTable of soprano voice
  631.     rAltoVox                = 9013,        //snd containing waveTable of alto voice
  632.     rTenorVox                = 9014,        //snd containing waveTable of tenor voice
  633.     rBassVox                = 9015,        //snd containing waveTable of bass voice
  634.  
  635.     rSampleHarmony            = 9016,        //snd containing the sampled sound harmony
  636.     rSampleMelody            = 9017        //snd containing the sampled sound melody
  637. };
  638.  
  639. //The following are resource IDs for messages.
  640. enum {
  641.     sErrStrings                = 1000,        //error string STR# ID
  642.     sStandardErr            = 1,        //An error has occurred.
  643.     sMemErr                    = 2,        //A Memory Manager error has occurred.
  644.     sResErr                    = 3,        //A Resource Manager error has occurred.
  645.     sCurInUseErr            = 4,        //That file is currently in use.
  646.     sWavesBroken            = 5,        //The wave table synthesizer is not available.
  647.     sWrongVersion            = 6,        //This system does not support the Sound Manager...
  648.     sLowMemory                = 7,        //Memory is too low to continue...
  649.     sNoMenus                = 8,        //Could not find application’s menu resources.
  650.     sInitSoundErr            = 9,        //Could not initialize the SoundUnit.
  651.     sSoundErr                = 10,        //The Sound Manager has encountered an error.
  652.     sNewDocErr                = 11,        //Could not create a new document.
  653.     sInitStatusErr            = 12,        //Error initializing the status window.
  654.     sEditErr                = 13,        //Could not complete the edit command.
  655.     sDocErr                    = 14,        //There is a problem with this document.
  656.  
  657.     sMsgStrings                = 1001,        //message string STR# ID
  658.     sPlayingMsg                = 1,        //playing a sound
  659.     sHyperMsg                = 2,        //playing a sound the Hyper way
  660.     sScaleMsg                = 3,        //playing scale
  661.     sMelodyMsg                = 4,        //playing melody
  662.     sTimbresMsg                = 5,        //playing various timbres
  663.     sCounterPtMsg            = 6,        //playing 4 part counter point
  664.  
  665.     sSMErrStrings            = 1002        //strings describing Sound Manager errors
  666. };
  667.  
  668. /*
  669. The following constants are used to identify menus and items. The menu IDs
  670. have an “m” prefix and the item numbers within each menu have an “i” prefix.
  671. */
  672.  
  673. enum {
  674.     mApple                    = 128,        //Apple menu and items
  675.     iAbout                    = 1,
  676.  
  677.     mFile                    = 129,        //File menu and items
  678.     iNew                    = 1,
  679.     iOpen                    = 2,
  680.     iClose                    = 4,
  681.     iQuit                    = 12,
  682.  
  683.     mEdit                    = 130,        //Edit menu and items
  684.     iUndo                    = 1,
  685.     iCut                    = 3,
  686.     iCopy                    = 4,
  687.     iPaste                    = 5,
  688.     iClear                    = 6,
  689.  
  690.     mDemos                    = 1000,        //Demos menu and items
  691.     iCheckVolume            = 1,
  692.     iSquareScale            = 3,
  693.     iSquareMelody            = 4,
  694.     iSquareTimbre            = 5,
  695.     iWaveScale                = 7,
  696.     iWaveMelody                = 8,
  697.     iWaveSATB                = 9,
  698.     iSampleMelody            = 11,
  699.     iSampleSATB                = 12
  700. };
  701.  
  702.  
  703. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  704. // macros
  705. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  706.  
  707. // Define HighWord and LowWord macros for efficiency.
  708. #define HighWord(aLong)        ((aLong) >> 16)
  709. #define LowWord(aLong)        ((aLong) & 0x0000FFFF)
  710.  
  711. // accessing a rectangle's points
  712. #define TopLeft(r)            (* (Point *) &(r).top)
  713. #define BottomRight(r)        (* (Point *) &(r).bottom)
  714.  
  715. #define AbsoluteValue(n)    ((n > 0) ? n : -n)
  716.  
  717. #if GENERATINGCFM
  718. #define CreateRoutineDescriptor(info, proc)                                    \
  719.  RoutineDescriptor g##proc##RD = BUILD_ROUTINE_DESCRIPTOR(info, proc)
  720.  
  721. #define GetRoutineAddress(proc)    (&g##proc##RD)
  722.  
  723. #else
  724. #define GetRoutineAddress(proc)    proc
  725. #endif
  726.  
  727. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  728. // types
  729. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  730.  
  731. typedef RectPtr *RectHandle;
  732.  
  733. /*
  734. This is a document layout that contains the window record and references
  735. to the associating data.  The window record MUST be the first field.  This
  736. is because I use the window pointer returned by the Toolbox to be a
  737. pointer to my document.  To confirm that the window pointer is a document
  738. pointer, I store an application reference in the window record’s refCon.
  739. Then, I use a routine to test for the presence of this reference to insure
  740. I’m looking at one of my document’s windows.
  741. */
  742.  
  743. struct SndDocument {
  744.     WindowRecord    window;                // must be first field
  745.     short             resFile;            // document’s resource file
  746.     short             vRefNum;
  747.     long             dirID;
  748.     ListHandle        list;                // document’s list of sounds
  749.     Boolean            sndInUse;            // document is using a 'snd ' resource
  750. };
  751. typedef struct SndDocument SndDocument;
  752. typedef SndDocument *SndDocPeek;        // to peek at the document record
  753.  
  754. // This is the status window layout.  The concept here is similar to the
  755. // document type mentioned above.  The message is a string handle used to
  756. // store the current message.
  757.  
  758. struct StatusWindow {
  759.     WindowRecord    window;
  760.     StringHandle    message;            // current text of status message
  761.     long            showTime;            // time window was shown
  762. };
  763. typedef struct StatusWindow StatusWindow;
  764. typedef StatusWindow *StatWindowPeek;
  765.  
  766. // This is the about window layout.  The concept here is similar to the
  767. // document type mentioned above.  The comment is a string handle used to
  768. // store the current message.
  769.  
  770. struct AboutWindow {
  771.     WindowRecord    window;
  772.     Handle            appPict;            // handle to picture of app’s name
  773.     Handle             comment;            // handle to string of about comments
  774. };
  775. typedef struct AboutWindow AboutWindow;
  776. typedef AboutWindow *AboutWPeek;
  777.  
  778. // This is the template to the WIND resource.  I used it to load in the WIND
  779. // resource and then adjust the boundsRect.  I also look at the procID to
  780. // determine if it has a title bar or drag region.
  781.  
  782. struct WindowTemplate {                    // template to a WIND resource
  783.     Rect        boundsRect;
  784.     short        procID;
  785.     Boolean        visible;
  786.     Boolean        filler1;
  787.     Boolean        goAwayFlag;
  788.     Boolean        filler2;
  789.     long        refCon;
  790.     Str255        title;
  791. };
  792. typedef struct WindowTemplate WindowTemplate;
  793. typedef WindowTemplate *WindowTPtr, **WindowTHndl;
  794.  
  795. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  796. // inlines
  797. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  798.  
  799. /*
  800. This is a handy routine to copy pascal strings. It's smaller than the
  801. library call pstrcopy, and faster too.
  802. */
  803.  
  804. #if GENERATING68K
  805. #pragma parameter PStringCopy(__A0,__A1)
  806. void PStringCopy(StringPtr source, StringPtr destination)
  807.  FIVEWORDINLINE (0x7000, 0x1010, 0x12D8, 0x51C8, 0xFFFC);
  808. //                    moveq    #0,d0
  809. //                    move.b    (a0),d0
  810. //            loop    move.b    (a0)+,(a1)+
  811. //                    dbra    d0,loop
  812. #else
  813. #include <DriverServices.h>
  814. #define PStringCopy(source, dest) PStrCopy(dest, source)
  815. #endif
  816.  
  817. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  818. // prototypes
  819. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  820.  
  821. short NumToolboxTraps(void);
  822. Boolean TrapExists(short theTrap);
  823. pascal long MyGrowZone(Size cbNeeded);
  824. Boolean LowOnReserve(void);
  825. void RecoverReserve(void);
  826. Boolean AllocateReserve(void);
  827. Boolean FailLowMemory(long memRequest);
  828. Boolean HasSelection(SndDocPeek sndDoc);
  829. OSErr GetSelection(SndDocPeek sndDoc, SndListHandle *sndHandle);
  830. void SelectNextCell(ListHandle list, Boolean next);
  831. void SelectSndCell(SndDocPeek sndDoc, short resID);
  832. OSErr InitSndList(SndDocPeek docPtr);
  833. Boolean OpenByApp(FSSpecPtr file, WindowPtr *window);
  834. Point GetGlobalMouse(void);
  835. short GetWTitleHeight(short variant);
  836. Point GetGlobalTopLeft(WindowPtr window);
  837. void MyParamText(StringHandle text, StringPtr cite0, StringPtr cite1);
  838. void CenterWindowRect(short variant, Rect *theRect);
  839. WindowPtr GetCenteredWindow(short id, Ptr p, WindowPtr behind);
  840. short CenteredAlert(short alertID);
  841. DialogPtr GetCenteredDialog(short id, Ptr p, WindowPtr behind);
  842. void DoButtonOutline(ControlHandle button);
  843. void SelectButton(ControlHandle button);
  844. void ActivateSndCntls(SndDocPeek sndDoc);
  845. Boolean IsDAWindow(WindowPtr window);
  846. Boolean IsDocWindow(WindowPtr window);
  847. Boolean IsModalWindow(WindowPtr window);
  848. void KillSound(void);
  849. Boolean DoCloseWindow(WindowPtr window);
  850. void AlertUser(short error, short messageID);
  851. void EmergencyExit(short message);
  852. void Terminate(void);
  853. void DrawStatusWindow(void);
  854. void ShowStatusWindow(short messageID);
  855. void InitStatusWindow(void);
  856. pascal void DoErrorSound(short soundNo);
  857. void CheckSoundVolume(void);
  858. void AddSndDocControls(WindowPtr window);
  859. Boolean PositionAvailable(Point newPt, short wTitleHeight);
  860. WindowPtr NewStackedWindow(short windID, Ptr windStorage);
  861. OSErr CreateSoundDoc(short resRef, FSSpecPtr file);
  862. void OpenSoundDoc(FSSpecPtr file);
  863. void NewSoundDoc(void);
  864. pascal Boolean SFFilter(CInfoPBPtr p, Boolean *sndFilesOnly);
  865. pascal short SFGetHook(short mySFItem, DialogPtr dialog, void *sndFilesOnly);
  866. void GetSoundDoc(void);
  867. void DrawAboutWindow(WindowPtr window);
  868. void DoAbout(void);
  869. void PlaySelectedSnd(SndDocPeek sndDoc, short message);
  870. void PlaySndSong(SndDocPeek sndDoc, short sndID);
  871. void PlaySquareSong(short sndID);
  872. void PlaySquareTimbres(void);
  873. void PlayWaveScale(void);
  874. OSErr GetSndSongs(short sndSongID1, short sndSongID2, short sndSongID3, short sndSongID4, SndListHandle *sndSong1, SndListHandle *sndSong2, SndListHandle *sndSong3, SndListHandle *sndSong4);
  875. OSErr InstallWaveSnds(SndChannelPtr chan1, SndChannelPtr chan2, SndChannelPtr chan3, SndChannelPtr chan4, short waveID1, short waveID2, short waveID3, short waveID4);
  876. void PlayWaveMelody(void);
  877. void PlayWaveSATB(void);
  878. void PlaySampleMelody(void);
  879. void PlaySampleSATB(void);
  880. pascal void DefaultOutline(WindowPtr window, short theItem);
  881. void GetSndName(Str255 sndName);
  882. OSErr AddSnd(SndDocPeek sndDoc, StringPtr sndNamePtr, SndListHandle sndHndl);
  883. void ClearSnd(SndDocPeek sndDoc);
  884. void DoRecordSound(SndDocPeek sndDoc);
  885. void AdjustMenus(void);
  886. void CopySnd(SndDocPeek sndDoc);
  887. void CutSnd(SndDocPeek sndDoc);
  888. void PasteSnd(SndDocPeek sndDoc);
  889. void DoMenuCommand(long menuResult);
  890. void DrawSndWindow(WindowPtr window);
  891. void DoKeyDown(char key, WindowPtr window);
  892. Boolean ListClick(SndDocPeek sndDoc, EventRecord *event);
  893. void DoSndDocClick(SndDocPeek sndDoc, EventRecord *event);
  894. void DoStatClick(StatWindowPeek statWindow, EventRecord *event);
  895. void DoAboutClick(WindowPtr window, EventRecord *event);
  896. void DoUpdate(WindowPtr window);
  897. void DoActivate(WindowPtr window, Boolean becomingActive);
  898. pascal OSErr QuitApplicationEvent(const AppleEvent *theAppleEvent, AppleEvent *reply, long handlerRefcon);
  899. pascal OSErr OpenDocumentsEvent(const AppleEvent *theAppleEvent, AppleEvent *reply, long handlerRefcon);
  900. pascal OSErr PrintDocumentsEvent(const AppleEvent *theAppleEvent, AppleEvent *reply, long handlerRefcon);
  901. pascal OSErr OpenApplicationEvent(const AppleEvent *theAppleEvent, AppleEvent *reply, long handlerRefcon);
  902. void DoEvent(EventRecord *event);
  903. void AdjustCursor(RgnHandle region);
  904. void EventLoop(void);
  905. void Initialize(void);
  906. void main(void);
  907.  
  908. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  909. // Globals (The “g” prefix is used to emphasize that a variable is global.)
  910. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  911.  
  912. /*
  913. gMac is used to hold the result of a SysEnvirons call. This makes it
  914. convenient for any routine to check the environment. It is considered
  915. global information, anyway.
  916. */
  917.  
  918.     SysEnvRec gMac;                    //set up by Initialize
  919.  
  920. /*
  921. gReserveMemory is a handle of reserve memory used by my grow zone
  922. procedure.  If memory is attempted to be allocated and fails, my grow
  923. zone will release this reserved block of memory.
  924. */
  925.  
  926.     Handle gReserveMemory;
  927.  
  928. /*
  929. gStatusWindow is the window that tells the user what’s happening.  I show
  930. it while a sound is playing, and remove it as soon as the sound is
  931. complete.  It is initialized once during startup, and from then on two
  932. routines are used to show and hide it.  This demonstrates orchestrating
  933. multimedia, that sound/graphic idea, at least in a crude sort of way.
  934. */
  935.  
  936.     StatWindowPeek gStatusWindow;
  937.  
  938. /*
  939. gAppResRef is the application’s resource file reference.  I need to save
  940. this since I can open other resource files.  The current resource file is
  941. always gAppResRef unless I momentarily set it to another file to read its
  942. resources, and then immediately restore it back.
  943. */
  944.  
  945.     short gAppResRef;                //set up by Initialize
  946.  
  947. /*
  948. gInBackground is maintained by our osEvent handling routines. Any part of
  949. the program can check it to find out if it is currently in the background.
  950. */
  951.  
  952.     Boolean gInBackground;            //maintained by Initialize and DoEvent
  953.  
  954. /*
  955. We have to allocate our own QuickDraw globals when creating code for PowerMacs.
  956. MetroWerks declares "qd" in their runtime, so don't do that twice.
  957. */
  958.  
  959. #if GENERATINGCFM && !defined(__MWERKS__)
  960.     QDGlobals    qd;
  961. #endif
  962.  
  963. /*
  964. This is necessary because of the Apple Event Manager. We used to be able
  965. to quit directly when the user choose Quit from the File menu. But because
  966. of the design of Apple Events, we cannot call ExitToShell from the quit handler.
  967. That event handler must set a flag and then check it in the event loop.
  968. */
  969.  
  970.     Boolean gTerminate;
  971.  
  972.  
  973. // allocate the RoutineDescriptors for Power Mac toolbox calls
  974. #if GENERATINGCFM
  975. CreateRoutineDescriptor(uppGrowZoneProcInfo, MyGrowZone);
  976. CreateRoutineDescriptor(uppFileFilterYDProcInfo, SFFilter);
  977. CreateRoutineDescriptor(uppDlgHookYDProcInfo, SFGetHook);
  978. CreateRoutineDescriptor(uppUserItemProcInfo, DefaultOutline);
  979. CreateRoutineDescriptor(uppUserItemProcInfo, QuitApplicationEvent);
  980. CreateRoutineDescriptor(uppUserItemProcInfo, OpenDocumentsEvent);
  981. CreateRoutineDescriptor(uppUserItemProcInfo, PrintDocumentsEvent);
  982. CreateRoutineDescriptor(uppUserItemProcInfo, OpenApplicationEvent);
  983. #endif
  984.  
  985. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  986. // IMPLEMENTATION
  987. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  988.  
  989. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  990. /*
  991. InitGraf is always implemented (trap 0xA86E). If the trap table is big
  992. enough, trap 0xAA6E will always point to either Unimplemented or some other
  993. trap, but will never be the same as InitGraf. Thus, you can check the size
  994. of the trap table by asking if the address of trap 0xA86E is the same as 0xAA6E.
  995. */
  996.  
  997. #pragma segment Initialize
  998. short NumToolboxTraps(void)
  999. {
  1000.     if ( GetToolboxTrapAddress(_InitGraf) == GetToolboxTrapAddress(_InitGraf + 0x0200) )
  1001.         return (0x0200);
  1002.     else
  1003.         return (0x0400);
  1004. }
  1005.  
  1006. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1007. /*
  1008. Check to see if a given trap is implemented.  GetTrapAddress may screw up and
  1009. wrap around into the trap table if you give it a toolbox trap that is out of
  1010. range, so check for this first.
  1011. */
  1012.  
  1013. #pragma segment Initialize
  1014. Boolean TrapExists(short theTrap)
  1015. {
  1016.     UniversalProcPtr    trapAddress;
  1017.  
  1018.     if ( !(theTrap & kOSTrapBit) )                        // is this an OS trap?
  1019.         trapAddress = GetOSTrapAddress(theTrap);
  1020.     else {                                                // no, this is a tool trap
  1021.         theTrap &= kTrapNumberMask;                        // get the trap number
  1022.         if ( theTrap < NumToolboxTraps() )                // can this tool trap exist?
  1023.             trapAddress = GetToolTrapAddress(theTrap);
  1024.         else
  1025.             return (false);
  1026.     }
  1027.     return ( GetToolboxTrapAddress(_Unimplemented) != trapAddress );
  1028. }
  1029.  
  1030. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1031. /*
  1032. This is a very basic grow zone procedure.  My application keeps a reserve
  1033. handle of memory in case the Memory Manager gets a request for some memory
  1034. that is not available in my heap.  If memory were to get tight (<32k),
  1035. the Toolbox will crash the system, especially Quickdraw.  Before releasing
  1036. the reserve handle I make sure it isn’t the GZSaveHnd.  This handle cannot
  1037. be touched by the grow zone procedure.
  1038.  
  1039. WARNING:  The grow zone procedure will be called and A5 may not be valid.
  1040. Read Tech Note #136 and 208
  1041. */
  1042.  
  1043. #pragma segment Main
  1044. pascal long MyGrowZone(Size cbNeeded)
  1045. {
  1046. #pragma unused (cbNeeded)
  1047.     long theA5;
  1048.     long result;
  1049.  
  1050.     theA5= SetCurrentA5();
  1051.     if (((*gReserveMemory) != nil) && (gReserveMemory != GZSaveHnd())) {
  1052.         EmptyHandle(gReserveMemory);
  1053.         result = kSizeOfReserve;                    //released this much memory
  1054.     } else
  1055.         result = 0;                                //this may release more memory
  1056.     theA5= SetA5(theA5);
  1057.     return(result);
  1058. }
  1059.  
  1060. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1061. /*
  1062. Before my application attempts to use more memory, I call this routine
  1063. to check if I’m already using my reserve memory.  If so, then I better
  1064. prepare to die or get my reserve back.
  1065. */
  1066.  
  1067. #pragma segment Main
  1068. Boolean LowOnReserve(void)
  1069. {
  1070.     return((*gReserveMemory) == nil);        // empty handle is low reserve
  1071. }
  1072.  
  1073. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1074. /*
  1075. This is called from the event loop if LowOnReserve returns that I’m out of
  1076. the reserve memory.  This will recover the reserve memory block.  If this
  1077. fails, it will be called the next time through the event loop.
  1078. */
  1079.  
  1080. #pragma segment Main
  1081. void RecoverReserve(void)
  1082. {
  1083.     ReallocateHandle(gReserveMemory, kSizeOfReserve);
  1084. }
  1085.  
  1086. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1087. /*
  1088. This is called at startup time to allocate the reserve memory block used
  1089. in the grow zone procedure.  If I’m unable to obtain this reserve, then
  1090. return false to signal a failure.
  1091. */
  1092.  
  1093. #pragma segment Initialize
  1094. Boolean AllocateReserve(void)
  1095. {
  1096.     gReserveMemory = NewHandle(kSizeOfReserve);
  1097.     return(gReserveMemory != nil);
  1098. }
  1099.  
  1100. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1101. /*
  1102. Call PurgeSpace and see if the requested amount of memory exists in the
  1103. heap including a minimal amount of heap space.  Also, if my grow zone’s
  1104. reserve has been release, that’s considered a failure.  I don’t perform
  1105. any purging here.  The Memory Manager will do this if it needs the space.
  1106. This routine can be called with a memRequest == 0.  This checks if the heap
  1107. space is getting critical.
  1108. */
  1109.  
  1110. #pragma segment Main
  1111. Boolean FailLowMemory(long memRequest)
  1112. {
  1113.     long    total;
  1114.     long    contig;
  1115.  
  1116.     PurgeSpace(&total, &contig);
  1117.     return((total < (memRequest + kMinSpace)) || LowOnReserve());
  1118. }
  1119.  
  1120. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1121. /*
  1122. This a simple test to see if the user has a currently selected list item.
  1123. */
  1124.  
  1125. #pragma segment Main
  1126. Boolean HasSelection(SndDocPeek sndDoc)
  1127. {
  1128.     Cell aCell;
  1129.  
  1130.     SetPt(&aCell, 0, 0);
  1131.     return(LGetSelect(true, &aCell, sndDoc->list));
  1132. }
  1133.  
  1134. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1135. /*
  1136. Given a document, this will find the currently selected cell in the list.
  1137. Then using this cell as an index number, I call Get1IndResource.  This
  1138. will return the proper handle.  Since the List Manager is zero based and
  1139. the Resource Manager isn’t, I have to add one to the index.
  1140.  
  1141. BUG NOTE: GetIndResource will return a bogus handle if the index is not
  1142. positive.
  1143. */
  1144.  
  1145. #pragma segment Main
  1146. OSErr GetSelection(SndDocPeek sndDoc, SndListHandle *sndHandle)
  1147. {
  1148.     Cell    aCell;
  1149.     OSErr    result;
  1150.  
  1151.     result = noErr;
  1152.     SetPt(&aCell, 0, 0);
  1153.     if (LGetSelect(true, &aCell, sndDoc->list)) {
  1154.         if (aCell.v > -1) {                        // GetIndResource doesn’t like < 0
  1155.             UseResFile(sndDoc->resFile);        // only get our resources
  1156.             *sndHandle = (SndListHandle)Get1IndResource(soundListRsrc, aCell.v + 1);
  1157.             if (*sndHandle == nil)
  1158.                 result = ResError();            // return any error
  1159.             UseResFile(gAppResRef);                // restore our resource file
  1160.         }
  1161.     }
  1162.     return(result);
  1163. }
  1164.  
  1165. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1166. /*
  1167. This is used to allow the user to select items from the list by using
  1168. the arrow keys.  Given a list and the direction, this will select the
  1169. next cell.  It will do nothing if we’re at the first cell and the user
  1170. wants to do even higher (sped), or if we’re at the last cell and the
  1171. user wants to go even lower (rent a clue bud).
  1172. */
  1173.  
  1174. #pragma segment Main
  1175. void SelectNextCell(ListHandle list, Boolean next)
  1176. {
  1177.     Cell    aCell;
  1178.     short    lastItem;
  1179.  
  1180.     lastItem = (**list).dataBounds.bottom - 1;        // bounds is 1 greater
  1181.     SetPt(&aCell, 0, 0);
  1182.     if (LGetSelect(true, &aCell, list)) {
  1183.         if ((next && (aCell.v < lastItem)) || ((!next) && (aCell.v > 0))) {
  1184.             LSetSelect(false, aCell, list);
  1185.             if (next)
  1186.                 aCell.v = aCell.v + 1;
  1187.             else
  1188.                 aCell.v = aCell.v - 1;
  1189.             SetPt(&aCell, aCell.h, aCell.v);
  1190.             LSetSelect(true, aCell, list);
  1191.             LAutoScroll(list);
  1192.         }
  1193.     }
  1194.     else                                            // if no cells selected...
  1195.         LSetSelect(true, aCell, list);                // select the first cell
  1196. }
  1197.  
  1198. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1199. /*
  1200. VERSION 1.1:  This routine will go through the list of snd resources
  1201. looking for the one that has the resource ID matching the parameter passed
  1202. in.  First thing to do is deselect the current selection.  Then once the
  1203. matching resource is found, select that one and scroll it into view.  One
  1204. assumption made is that the resources and the list are both index in the
  1205. same order.  This is true for the sndDoc, since I built the list this way.
  1206. */
  1207.  
  1208. #pragma segment Main
  1209. void SelectSndCell(SndDocPeek sndDoc, short resID)
  1210. {
  1211.     Str255 name;
  1212.     Cell aCell;
  1213.     Handle sndHndle;
  1214.     ResType rType;
  1215.     short testID;
  1216.     short index;
  1217.     short numSnd;
  1218.  
  1219.     index = 0;
  1220.     aCell.h = 0;
  1221.     aCell.v = 0;
  1222.     if (LGetSelect(true, &aCell, sndDoc->list))
  1223.         LSetSelect(false, aCell, sndDoc->list); //deselect any cell
  1224.     UseResFile(sndDoc->resFile);                //count only its resources
  1225.     numSnd = Count1Resources(soundListRsrc);    //number of sounds available
  1226.     do {
  1227.         index++;
  1228.         SetResLoad(false);                        //don’t load any resources
  1229.         sndHndle = Get1IndResource(soundListRsrc, index); //only get snd from file
  1230.         SetResLoad(true);                            //back to normal resource operations
  1231.         GetResInfo(sndHndle, &testID, &rType, name);
  1232.     } while ((resID != testID) && (index < numSnd));
  1233.  
  1234.     UseResFile(gAppResRef);                        //restore our resource file
  1235.     aCell.h = 0;
  1236.     aCell.v = index - 1;
  1237.     LSetSelect(true, aCell, sndDoc->list);
  1238.     LAutoScroll(sndDoc->list);
  1239. }
  1240.  
  1241. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1242. /*
  1243. This is used to create the list showing all the snd resources in the file.
  1244. If anything goes wrong while attempting to get any of the resources, then I
  1245. return false.  I don’t want the document to continue if something goes
  1246. wrong while reading a resource.  If I do get the resource, then I add its
  1247. name to the list in a new row.  I’m assured that at least one resource is
  1248. in the file before this routine is called.  Untitled resources will get one.
  1249. */
  1250.  
  1251. #pragma segment Open
  1252. OSErr InitSndList(SndDocPeek docPtr)
  1253. {
  1254.     short            index;
  1255.     short            resID;
  1256.     short            newRow;
  1257.     short            numSnd;
  1258.     Handle            resHandle;
  1259.     StringHandle    strHandle;
  1260.     ResType            itsType;
  1261.     Str255            resName;
  1262.     Str255            untitled;
  1263.     Cell            aCell;
  1264.     OSErr            result = noErr;
  1265.  
  1266.     strHandle = (StringHandle)Get1Resource('STR ', rUntitled);
  1267.     if (strHandle != nil)
  1268.         PStringCopy(*strHandle, untitled);        // save no name title
  1269.     else
  1270.         untitled[0] = 0;                        // at least an empty string
  1271.     UseResFile(docPtr->resFile);
  1272.     numSnd = Count1Resources(soundListRsrc);
  1273.     newRow = LAddRow(numSnd, 0, docPtr->list);
  1274.     for (index = 1; index <= numSnd; index++) {
  1275.         SetResLoad(false);                        // don’t load any resources
  1276.         resHandle = Get1IndResource(soundListRsrc, index); // only get snd from file
  1277.         SetResLoad(true);                        // back to normal operations
  1278.         if (resHandle != nil) {                    // only if I got the snd
  1279.             GetResInfo(resHandle, &resID, &itsType, resName);
  1280.             if (StrLength(resName) == 0)        // if the snd isn’t named...
  1281.                 PStringCopy(untitled, resName);    // give it a name
  1282.             SetPt(&aCell, 0, index - 1);
  1283.             LSetCell(&resName[1], StrLength(resName), aCell, docPtr->list);
  1284.         }
  1285.         else {                                     // resHandle == NIL
  1286.             result = resNotFound;                // problem with resource file
  1287.             break;                                // get out of the loop
  1288.         }
  1289.     }
  1290.     UseResFile(gAppResRef);                        // restore our resource file
  1291.     return(result);
  1292. }
  1293.  
  1294. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1295. /*
  1296. In the case that the user has attempted to open a resource file that is
  1297. already open, this routine will scan my open documents for it.  If I find
  1298. that the requested file is already open by the application, then return
  1299. true and its window pointer.  The application can then simply select that
  1300. window.  If the resource file is open but not by this application, that’s
  1301. a problem and I don’t use the resource file.  Many problems with using an
  1302. open resource file.  Now if the Resource Manager would take care of this
  1303. problem for us...
  1304. */
  1305.  
  1306. #pragma segment Open
  1307. Boolean OpenByApp(FSSpecPtr file, WindowPtr *window)
  1308. {
  1309.     Str255 docName;
  1310.     WindowPtr testWindow;
  1311.     Boolean result;
  1312.  
  1313.     result = false;
  1314.     testWindow = FrontWindow();
  1315.     while (testWindow != nil) {
  1316.         if (GetWRefCon(testWindow) == rSoundWindow)
  1317.             if ((file->vRefNum == ((SndDocPeek)testWindow)->vRefNum)
  1318.                 && (file->parID == ((SndDocPeek)testWindow)->dirID))
  1319.             {
  1320.                 GetWTitle(testWindow, docName);
  1321.                 if (EqualString(file->name, docName, false, true))
  1322.                 {
  1323.                     *window = testWindow;
  1324.                     result = true;
  1325.                     break;
  1326.                 }
  1327.             }
  1328.         testWindow = (WindowPtr)(((WindowPeek)testWindow)->nextWindow);
  1329.     }
  1330.     return(result);
  1331. }
  1332.  
  1333. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1334. /*
  1335. Get the global coordinates of the mouse.  Get the global coordinates by
  1336. calling GetMouse and LocalToGlobal.  This assumes the current port is a
  1337. valid graf port.  When wouldn’t it be?
  1338. */
  1339.  
  1340. #pragma segment Main
  1341. Point GetGlobalMouse(void)
  1342. {
  1343.     Point globalPt;
  1344.  
  1345.     GetMouse(&globalPt);
  1346.     LocalToGlobal(&globalPt);
  1347.     return(globalPt);
  1348. }
  1349.  
  1350. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1351. /*
  1352. Try and determine the window’s title bar height.  This isn’t easy,
  1353. especially if the window is invisible.  We all know how the standard Apple
  1354. System WDEF works, at least at this date we do.  I assume that method as
  1355. shown below.  I could do what MacApp does with the Function CallWDefProc.
  1356. If the user has installed a replacement for the System WDEF, then it’s
  1357. their problem to deal with.  My method will work as long as Apple doesn’t
  1358. change how the WDEF in System 6.0 calculates the title bar height.  This
  1359. will allow my application to work on international Macs that have a larger
  1360. system font than Chicago.  I check the window’s variant code for one that
  1361. includes a title bar.  I will have to change this routine to adjust for
  1362. the modal-moveable window type, which hasn’t been defined yet.
  1363.  
  1364. In this routine, I violate my rule about not using the GetPort, SetPort,
  1365. SetPort sequence mentioned at the start of the file. Mostly, I do this
  1366. because it’s not all that apparent that a routine called GetWTitleHeight
  1367. will change the port, so I make sure that it doesn’t.
  1368. */
  1369.  
  1370. #pragma segment Open
  1371. short GetWTitleHeight(short variant)
  1372. {
  1373.     FontInfo info;
  1374.     GrafPtr curGraf;
  1375.     GrafPtr wMgrPort;
  1376.     short wTitleHeight;
  1377.     short result;
  1378.  
  1379.     if (    (variant == documentProc)
  1380.          || (variant == noGrowDocProc)
  1381.          || (variant == zoomDocProc)
  1382.          || (variant == rDocProc) )
  1383.     {
  1384.         GetPort(&curGraf);
  1385.         GetWMgrPort(&wMgrPort);                        //I need to know the font...
  1386.         SetPort(wMgrPort);                            //info in the System’s port
  1387.         GetFontInfo(&info);
  1388.         SetPort(curGraf);                            //restore current port
  1389.         wTitleHeight = info.ascent + info.descent + info.leading + 2;
  1390.         if (wTitleHeight < kMinWindowTitleHeight)
  1391.             wTitleHeight = kMinWindowTitleHeight;
  1392.         result = wTitleHeight;
  1393.     } else
  1394.         result = 0;                            //other window types have no title
  1395.     return(result);
  1396. }
  1397.  
  1398. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1399. /*
  1400. Given a window, this will return the top left point of the window’s
  1401. port in global coordinates.  Something this doesn’t include, is the
  1402. window’s drag region (or title bar).  This returns the top left point
  1403. of the window’s content area only.
  1404.  
  1405. In this routine, I violate my rule about not using the GetPort, SetPort,
  1406. SetPort sequence mentioned at the start of the file. Mostly, I do this
  1407. because it’s not all that apparent that a routine called GetGlobalTopLeft
  1408. will change the port, so I make sure that it doesn’t.
  1409. */
  1410.  
  1411. #pragma segment Main
  1412. Point GetGlobalTopLeft(WindowPtr window)
  1413. {
  1414.     GrafPtr theGraf;
  1415.     Point globalPt;
  1416.  
  1417.     GetPort(&theGraf);
  1418.     SetPort(window);
  1419.     globalPt = TopLeft(window->portRect);
  1420.     LocalToGlobal(&globalPt);
  1421.     SetPort(theGraf);
  1422.     return(globalPt);
  1423. }
  1424.  
  1425. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1426. /*
  1427. I’m using string pointers (not necessarily Memory Manager pointers)
  1428. to the replacement strings.  Using Str255 would copy the string to the
  1429. stack, and then to the text handle.  This way it is only copied once.
  1430. */
  1431.  
  1432. #pragma segment Main
  1433. void MyParamText(StringHandle text, StringPtr cite0, StringPtr cite1)
  1434. {
  1435.     long    offSet;
  1436.     char    param0[2] = {'^', '0'};
  1437.     char    param1[2] = {'^', '1'};
  1438.     long    newLength;
  1439.  
  1440.     if (StrLength(cite0) > 0)
  1441.         offSet = Munger((Handle)text, 1, param0, sizeof(param0), (Ptr)&(cite0[1]), StrLength(cite0));
  1442.     if (StrLength(cite1) > 0)
  1443.         offSet = Munger((Handle)text, 1, param1, sizeof(param1), (Ptr)&(cite1[1]), StrLength(cite1));
  1444.     newLength = GetHandleSize((Handle)text) - 1;
  1445.     if (newLength > 255)
  1446.         newLength = 255;
  1447.     (*text)[0] = newLength;                        // string’s new length byte
  1448. }
  1449.  
  1450. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1451. /*
  1452. Given a window’s portRect, this routine will center the rectangle on the
  1453. main device within the desktop region.  This excludes the menu bar area.
  1454. It follows the Apple Human Interface Guidelines for where to place a
  1455. window centered on the screen. That is, 1/3th of the desktop shows above
  1456. the window and 2/3ths below it.  It returns a new rectangle set to the
  1457. centered position.  The top and left of this rectangle can be used with
  1458. MoveWindow.  This routine only considers the main device.  CenterWindowRect
  1459. could take a GDevice as a parameter to center the VAR rect with.  This
  1460. would also allow Alerts or dialogs that are closely associated with a
  1461. document window to be centered relative to the monitor that contains that
  1462. document.  This is also one of the Human Interface Guidelines.  MacApp 2.0
  1463. has a utility CalcScreenRect that you can borrow from to include this.
  1464.  
  1465. WARNING: This routine may move or purge memory.
  1466. */
  1467.  
  1468. #pragma segment Open
  1469. void CenterWindowRect(short variant, Rect *theRect)
  1470. {
  1471.     Point rectSize;
  1472.     short wTitleHeight;
  1473.  
  1474.     wTitleHeight = GetWTitleHeight(variant);        //get title height
  1475.     SetPt(&rectSize, theRect->right, theRect->bottom + wTitleHeight);    //get size of rect
  1476.     SubPt(TopLeft(*theRect), &rectSize);            // include it in size
  1477.  
  1478.     theRect->top = ((qd.screenBits.bounds.bottom - qd.screenBits.bounds.top - GetMBarHeight() - rectSize.v)
  1479.                         / 3) + GetMBarHeight();        //1/3th below menubar, centered horz
  1480.     theRect->left = ((qd.screenBits.bounds.right - qd.screenBits.bounds.left) - rectSize.h) / 2;
  1481.  
  1482.     SetPt(&BottomRight(*theRect), theRect->left, theRect->top);    //return adjusted rect
  1483.     AddPt(rectSize, &BottomRight(*theRect));
  1484.     theRect->top += wTitleHeight;                    //remove title height from rect
  1485. }
  1486.  
  1487. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1488. /*
  1489. Given a window ID, this routine will center the window’s rectangle before
  1490. showing it on the main screen.  This follows the Apple Human Interface
  1491. Guidelines for where to place a centered window on the screen.  If the
  1492. window is closely associated with another window, considerations should be
  1493. given to where that other window is located.  If this other window is on a
  1494. screen other then the main monitor, then it would be best to center the
  1495. window on that other monitor.
  1496.  
  1497. VERSION 1.1: There is a problem with GetNewWindow in the old Mac Plus and
  1498. SE ROMS.  It will call ReleaseResource on the 'WIND' resource within
  1499. GetNewWindow.  This make the handle invalid after the call.  Therefore,
  1500. before calling HPurge, we get the resource once again.
  1501. */
  1502.  
  1503. #pragma segment Open
  1504. WindowPtr GetCenteredWindow(short id, Ptr p, WindowPtr behind)
  1505. {
  1506.     Rect newRect;
  1507.     WindowTHndl windTemplate;
  1508.     WindowPtr window;
  1509.  
  1510.     window = nil;                                                //initialize result
  1511.     windTemplate = (WindowTHndl)(Get1Resource('WIND', id));
  1512.     if (windTemplate != nil) {
  1513.         HNoPurge((Handle)windTemplate);
  1514.         newRect = (**windTemplate).boundsRect;
  1515.         CenterWindowRect((**windTemplate).procID, &newRect);
  1516.         (**windTemplate).boundsRect = newRect;
  1517.         window = GetNewWindow(id, p, behind);
  1518.         HPurge(Get1Resource('WIND', id));
  1519.     }
  1520.     return(window);
  1521. }
  1522.  
  1523. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1524. /*
  1525. Given an Alert ID, this routine will center the alert’s rectangle before
  1526. showing it on the main screen.  This follows the Apple Human Interface
  1527. Guidelines for where to place a centered window on the screen.  If the
  1528. Alert is closely associated with another window, considerations should be
  1529. given to what the window is located.  If this other window is on a screen
  1530. other then the main monitor, then it would be best to center the Alert on
  1531. that other monitor.
  1532.  
  1533. VERSION 1.2: System 7 supports auto-positioning of windows and dialog, so
  1534. this routine isn't being called anymore. I has been left in the sources
  1535. for the readers that may be interested in knowing how it works.
  1536. */
  1537.  
  1538. #pragma segment Open
  1539. short CenteredAlert(short alertID)
  1540. {
  1541.     AlertTHndl alertHandle;
  1542.     Rect alertRect;
  1543.  
  1544.     alertHandle = (AlertTHndl)(Get1Resource('ALRT', alertID));
  1545.     if (alertHandle != nil) {
  1546.         HNoPurge((Handle)alertHandle);
  1547.         alertRect = (**alertHandle).boundsRect;
  1548.         CenterWindowRect(dBoxProc, &alertRect);
  1549.         (**alertHandle).boundsRect = alertRect;
  1550.         HPurge((Handle)alertHandle);
  1551.     }
  1552.     return(Alert(alertID, nil));
  1553. }
  1554.  
  1555. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1556. /*
  1557. Given a dialog ID, this routine will center the dialog’s rectangle before
  1558. showing it on the main screen.  This follows the Apple Human Interface
  1559. Guidelines for where to place a centered window on the screen.  If the
  1560. dialog is closely associated with another window, considerations should be
  1561. given to what the window is located.  If this other window is on a screen
  1562. other then the main monitor, then it would be best to center the dialog on
  1563. that other monitor.
  1564.  
  1565. VERSION 1.1: There is a problem with GetNewDialog in the old Mac Plus and
  1566. SE ROMS.  It will call ReleaseResource on the 'WIND' resource within
  1567. GetNewWindow.  This make the handle invalid after the call.  Therefore,
  1568. before calling HPurge, we get the resource once again.
  1569.  
  1570. VERSION 1.2: System 7 supports auto-positioning of windows and dialog, so
  1571. this routine isn't being called anymore. I has been left in the sources
  1572. for the readers that may be interested in knowing how it works.
  1573. */
  1574.  
  1575. #pragma segment Open
  1576. DialogPtr GetCenteredDialog(short id, Ptr p, WindowPtr behind)
  1577. {
  1578.     Rect newRect;
  1579.     DialogTHndl dlogTemplate;
  1580.     DialogPtr dialog;
  1581.  
  1582.     dialog = nil;                                                //initialize result
  1583.     dlogTemplate = (DialogTHndl)Get1Resource('DLOG', id);
  1584.     if (dlogTemplate != nil) {
  1585.         newRect = (**dlogTemplate).boundsRect;
  1586.         CenterWindowRect((**dlogTemplate).procID, &newRect);
  1587.         (**dlogTemplate).boundsRect = newRect;
  1588.         HNoPurge((Handle)dlogTemplate);
  1589.         dialog = GetNewDialog(id, p, behind);
  1590.         HPurge(Get1Resource('DLOG', id));
  1591.     }
  1592.     return(dialog);
  1593. }
  1594.  
  1595. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1596. /*
  1597. Given any control handle, this will draw an outline around it.  This is
  1598. used for the default button of a window.  The extra nice feature here is
  1599. that I’ll erase the outline for buttons that are inactive.  Seems like
  1600. there should be a Toolbox call for getting a control’s hilite state.
  1601. Since there isn’t, I have to look into the control record myself.  This
  1602. should be called for update and activate events.
  1603.  
  1604. The method for determining the oval diameters for the roundrect is a
  1605. little different than that recommended by Inside Mac.  IM I-407 suggests
  1606. that you use a hardcoded (16,16) for the diameters. However, this only
  1607. looks good for small roundrects. For larger ones, the outline doesn’t
  1608. follow the inner roundrect because the CDEF for simply buttons doesn’t
  1609. use (16,16). Instead, it uses half the height of the button as the
  1610. diameter. By using this formula, too, our outlines look better.
  1611.  
  1612. WARNING: This will set the current port to the control’s window.
  1613. */
  1614.  
  1615. #pragma segment Main
  1616. void DoButtonOutline(ControlHandle button)
  1617. {
  1618.     Rect theRect;
  1619.     PenState curPen;
  1620.     short buttonOval;
  1621.  
  1622.     if (button != nil) {
  1623.         SetPort((**button).contrlOwner);
  1624.         GetPenState(&curPen);
  1625.         PenNormal();
  1626.         theRect = (**button).contrlRect;
  1627.         InsetRect(&theRect, kButtonFrameInset, kButtonFrameInset);
  1628.         buttonOval = (theRect.bottom - theRect.top) / 2;
  1629.         if (((**button).contrlHilite == kControlNoPart))
  1630.             PenPat(&qd.black);
  1631.         else
  1632.             PenPat(&qd.gray);
  1633.         PenSize(kButtonFrameSize, kButtonFrameSize);
  1634.         FrameRoundRect(&theRect, buttonOval, buttonOval);
  1635.         SetPenState(&curPen);
  1636.     }
  1637. }
  1638.  
  1639. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1640. /*
  1641. Given the button control handle, this will cause the button to look as
  1642. if it has been clicked in.  This is nice to do for the user if they type
  1643. return or enter to select the default item.
  1644. */
  1645.  
  1646. #pragma segment Main
  1647. void SelectButton(ControlHandle button)
  1648. {
  1649.     unsigned long finalTicks;
  1650.  
  1651.     HiliteControl(button, kHiliteControlSelect);
  1652.     Delay(kDelayTime, &finalTicks);
  1653.     HiliteControl(button, kHiliteControlDeselect);
  1654. }
  1655.  
  1656. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1657. /*
  1658. Given a sound document, this routine goes through the control list looking
  1659. for a control that needs to be activated, or deactivated what ever the
  1660. case maybe.  The Play button is the default button, and it also needs its
  1661. outline drawn.  The Stop button is always active on the front most window.
  1662. This is true even if there is no selection made in the window’s list.  The
  1663. Stop button is a global action, regardless of what is happening in the window.
  1664.  
  1665. VERSION 1.1:  Stop button is only active while a sound is playing.
  1666. */
  1667.  
  1668. #pragma segment Main
  1669. void ActivateSndCntls(SndDocPeek sndDoc)
  1670. {
  1671.     ControlHandle control;
  1672.     long cntlRefCon;
  1673.     Boolean activate;
  1674.  
  1675.     activate = ((WindowPeek)sndDoc)->hilited && HasSelection(sndDoc);
  1676.     control = (ControlHandle)((WindowPeek)sndDoc)->controlList;
  1677.     while (control != nil) {
  1678.         cntlRefCon = GetControlReference(control);
  1679.         if (    (cntlRefCon == rPlaySndCntl)
  1680.              || (cntlRefCon == rHyperPlayCntl)
  1681.              || (cntlRefCon == rPlayScaleCntl)
  1682.              || (cntlRefCon == rMelodyCntl)) {
  1683.             if (activate)
  1684.                 HiliteControl(control, kControlNoPart);
  1685.             else
  1686.                 HiliteControl(control, kControlInactivePart);
  1687.             if (cntlRefCon == rPlaySndCntl)
  1688.                 DoButtonOutline(control);
  1689.         }
  1690.         if (cntlRefCon == rStopCntl) {
  1691.             if (((WindowPeek)sndDoc)->hilited && HasChannelOpen())
  1692.                 HiliteControl(control, kControlNoPart);
  1693.             else
  1694.                 HiliteControl(control, kControlInactivePart);
  1695.         } //cntlRefCon == rStopCntl
  1696.         if (cntlRefCon == rRecordCntl) {
  1697.             if (((WindowPeek)sndDoc)->hilited)
  1698.                 HiliteControl(control, kControlNoPart);
  1699.             else
  1700.                 HiliteControl(control, kControlInactivePart);
  1701.         } //cntlRefCon == rRecordCntl
  1702.         control = (**control).nextControl;
  1703.     }
  1704. }
  1705.  
  1706. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1707. /*
  1708. Check if a window belongs to a desk accessory.  This will first test for a
  1709. nil window.  DAs will have a negitive windowKind.
  1710. */
  1711.  
  1712. #pragma segment Main
  1713. Boolean IsDAWindow(WindowPtr window)
  1714. {
  1715.     if (window == nil)
  1716.         return(false);
  1717.     else    //DA windows have negative windowKinds
  1718.         return(((WindowPeek)window)->windowKind < 0);
  1719. }
  1720.  
  1721. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1722. /*
  1723. Check to see if a window is a document window.  This will first test for a
  1724. nil window.  Document windows all have a refCon set to rSoundWindow.  This
  1725. insures there is document type information after the window record.
  1726. */
  1727.  
  1728. #pragma segment Main
  1729. Boolean IsDocWindow(WindowPtr window)
  1730. {
  1731.     Boolean    result;
  1732.  
  1733.     if (window == nil)
  1734.         result = false;
  1735.     else
  1736.         result = (GetWRefCon(window) == rSoundWindow);
  1737.     return(result);
  1738. }
  1739.  
  1740. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1741. /*
  1742. This test will return true for a window that needs to be treated as a
  1743. modal window.  To include additional windows, add the window’s refCon
  1744. value to the set of modal windows.
  1745. */
  1746.  
  1747. #pragma segment Main
  1748. Boolean IsModalWindow(WindowPtr window)
  1749. {
  1750.     long    wRef;
  1751.     Boolean    result;
  1752.  
  1753.     if (window == nil)
  1754.         result = false;
  1755.     else {
  1756.         wRef = GetWRefCon(window);
  1757.         result = (wRef == rAboutWindow);         // test for all our modal windows
  1758.     }
  1759.     return(result);
  1760. }
  1761.  
  1762. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1763. /*
  1764. This is used to free up all the sound data and channels in use.  There are
  1765. two reasons for using this routine.  One is after a sound has completed
  1766. the other is to terminate a sound that may be in progress.  For this
  1767. second reason, this routine should always be used before playing a new
  1768. sound.  When disposing of a sound channel, this sets all document’s
  1769. sndInUse flags to false.  I can call this routine at any time.  When I
  1770. find that the memory reserve is used, I will call this to free up any
  1771. possible sound resources which tend to be large.  Another important point
  1772. is the human interface issue of hiding the status window.  It’s possible
  1773. that  playing some short sounds could cause the status window to disappear
  1774. before the user had much of a chance to see it.  To solve this, there is a
  1775. delay that insures the status window was visible for a minimal time.
  1776.  
  1777. VERSION 1.1:  Update the document's controls since know that the sound
  1778. is no longer playing the buttons in the document window need to be updated.
  1779. */
  1780.  
  1781. #pragma segment Main
  1782. void KillSound(void)
  1783. {
  1784.     WindowPtr window;
  1785.  
  1786.     if (HasChannelOpen()) {                            // if a channel is open...
  1787.         window = FrontWindow();                        // set all document’s flags
  1788.         while (window != nil) {
  1789.             if (IsDocWindow(window))                // if this is my document...
  1790.                 ((SndDocPeek)window)->sndInUse = false; // then it is no longer active
  1791.             window = (WindowPtr)((WindowPeek)window)->nextWindow;
  1792.         }
  1793.     }
  1794.     if (HasSoundCompleted()) {                        // why were we called?
  1795.         DoSoundComplete();                            // from completion
  1796.  
  1797.         // delay for status window to show a minimal amount of time
  1798.         while ((TickCount() - gStatusWindow->showTime) < kShowTimeDelay) {};
  1799.     }
  1800.     else
  1801.         FreeAllChans();                                // or just because
  1802.     HideWindow((WindowPtr)gStatusWindow);
  1803.     window = FrontWindow();
  1804.     if (IsDocWindow(window))
  1805.         ActivateSndCntls((SndDocPeek)window);
  1806. }
  1807.  
  1808. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1809. /*
  1810. Close any of my windows.  At this point, if there was a document
  1811. associated with a window, you could do any document saving processing if
  1812. it has been changed since being opened.  DoCloseWindow would return true
  1813. if the window actually closed.  false would be returned, as an example, if
  1814. the user chose “Cancel” in the Save As… dialog.  An important detail is if
  1815. the window to be close is one of my documents that is currently playing a
  1816. sound.  We cannot dispose of it yet, since the sound resource owned by the
  1817. document would be in use by the Sound Manager.  So, I test the document’s
  1818. sndInUse flag and if it is in use I call KillSound.  The About window
  1819. contains some resource handles.  I only mark them purgeable, but I could
  1820. use ReleaseResource and then DisposHandle.
  1821. */
  1822.  
  1823. #pragma segment Main
  1824. Boolean DoCloseWindow(WindowPtr window)
  1825. {
  1826.     Boolean        result = true;
  1827.  
  1828.     switch (GetWRefCon(window)) {
  1829.  
  1830.         case rSoundWindow:
  1831.             if (((SndDocPeek)window)->sndInUse)        // contain a snd in use?
  1832.                 KillSound();                        // not any more
  1833.             if (((SndDocPeek)window)->list != nil)    // dispose of document data
  1834.                 LDispose(((SndDocPeek)window)->list);
  1835.             if (((SndDocPeek)window)->resFile != 0)
  1836.                 CloseResFile(((SndDocPeek)window)->resFile);
  1837.             CloseWindow((WindowPtr)window);
  1838.             DisposePtr((Ptr)window);                // dispose of our doc storage
  1839.             break;
  1840.  
  1841.         case rStatusWindow:
  1842.             DisposeHandle((Handle)gStatusWindow->message);
  1843.             CloseWindow((WindowPtr)gStatusWindow);
  1844.             DisposePtr((Ptr)gStatusWindow);
  1845.             break;
  1846.  
  1847.         case rAboutWindow:
  1848.             if (((AboutWPeek)window)->comment != nil)    // never dispose...
  1849.                 HPurge(((AboutWPeek)window)->comment);    // a Resource handle
  1850.             if (((AboutWPeek)window)->appPict != nil)
  1851.                 HPurge(((AboutWPeek)window)->appPict);
  1852.             CloseWindow((WindowPtr)window);
  1853.             DisposePtr((Ptr)window);
  1854.             break;
  1855.  
  1856.         default:
  1857.             if (IsDAWindow(window))                        // we can close DAs too
  1858.                 CloseDeskAcc(((WindowPeek)window)->windowKind);
  1859.             break;
  1860.  
  1861.     } // switch GetWRefCon(window)
  1862.     return(result);
  1863. }
  1864.  
  1865. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1866. /*
  1867. Display an alert to inform the user of an error.  MessageID acts as an
  1868. index into a STR# resource of error messages.  This will attempt to
  1869. replace the error number with a string if the sound is a Sound Manager
  1870. error.
  1871.  
  1872. BUG NOTE: GetIndString will return a bogus string if the index is not
  1873. positive.
  1874. */
  1875.  
  1876. #pragma segment Main
  1877. void AlertUser(short error, short messageID)
  1878. {
  1879.     Str255    msg1;
  1880.     Str255    msg2;
  1881.     short    theItem;
  1882.  
  1883.     UseResFile(gAppResRef);                        // restore our resource file
  1884.     if (messageID > 0)
  1885.         GetIndString(msg1, sErrStrings, messageID);
  1886.     else
  1887.         msg1[0] = 0;                            // case there’s no message
  1888.     if ((error <= noHardware) && (error >= badFormat))
  1889.         GetIndString(msg2, sSMErrStrings, AbsoluteValue(error) + noHardware + 1);
  1890.     else
  1891.         NumToString(error, msg2);
  1892.     ParamText(msg1, msg2, "\p", "\p");
  1893.     theItem = Alert(rUserAlert, nil);
  1894. }
  1895.  
  1896. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1897. /*
  1898. Display an alert that tells the user an error occurred, then exit the
  1899. program.  This routine is used as an ultimate bail-out for serious errors
  1900. that prohibit the continuation of the application.  Errors that do not
  1901. require the termination of the application are handled with AlertUser.
  1902. Error checking and reporting has a place even in the simplest application.
  1903.  
  1904. BUG NOTE: GetIndString will return a bogus string if the index is not
  1905. positive.
  1906. */
  1907.  
  1908. #pragma segment Main
  1909. void EmergencyExit(short message)
  1910. {
  1911.     Str255    msg;
  1912.     short    theItem;
  1913.  
  1914.     SetCursor(&qd.arrow);
  1915.     if (message > 0)
  1916.         GetIndString(msg, sErrStrings, message);
  1917.     else
  1918.         msg[0] = 0;                                // case there’s no message
  1919.     ParamText(msg, "\p", "\p", "\p");
  1920.     theItem = Alert(rExitAlert, nil);
  1921.     ExitToShell();                                //gotta go!
  1922. }
  1923.  
  1924. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1925. /*
  1926. Clean up the application and exit.  I close all of the windows so that
  1927. they can update their documents, if any.  Dispose of the SoundUnit and
  1928. close the status window if the user really wants to quit.
  1929. */
  1930.  
  1931. #pragma segment Main
  1932. void Terminate(void)
  1933. {
  1934.     WindowPtr aWindow;
  1935.     Boolean closed;
  1936.  
  1937.     closed = true;
  1938.     KillSound();                                    //stop any sound in progress
  1939.     do {
  1940.         aWindow = FrontWindow();                    //get the current front window
  1941.         if (aWindow != nil)
  1942.             closed = DoCloseWindow(aWindow);        //close this window
  1943.     } while ((closed) && (aWindow != nil));            //do all windows
  1944.     if (closed) {
  1945.         FreeSoundUnit();                            //get rid of all sound equipment
  1946.         gTerminate = true;                            //exit if no cancellation
  1947.     }
  1948. }
  1949.  
  1950. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1951. /*
  1952. Draw the status message and update the button.  I setup a rectangle that
  1953. is the text area.  This is the entire window area, inset a small amount.
  1954. I also subtract from the bottom of the rectangle the area used by the button.
  1955. Doing things this way allowed me to change the size of the window and
  1956. not change any of this code.  The rectangle used by text will fill the
  1957. window regardless of the new size I give it in the WIND resource.
  1958. */
  1959.  
  1960. #pragma segment Main
  1961. void DrawStatusWindow(void)
  1962. {
  1963.     Rect    theRect;
  1964.  
  1965.     PenNormal();
  1966.     theRect = ((WindowPtr)gStatusWindow)->portRect;
  1967.     theRect.bottom = theRect.bottom - kDafaultButSizeH;
  1968.     InsetRect(&theRect, kStadardWhiteSpacing, kStadardWhiteSpacing);
  1969.     HLock((Handle)gStatusWindow->message);
  1970.     TETextBox((*(gStatusWindow->message) + 1),
  1971.                 **(gStatusWindow->message), &theRect, teJustLeft);
  1972.     HUnlock(((Handle)gStatusWindow->message));
  1973.     UpdateControls((WindowPtr)gStatusWindow, ((WindowPtr)gStatusWindow)->visRgn);
  1974.     DoButtonOutline((ControlHandle)((WindowPeek)gStatusWindow)->controlList);
  1975. }
  1976.  
  1977. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1978. /*
  1979. Whenever I start a sound, I show this status window.  It will contain a
  1980. message showing what is currently happening.  A very good rule is not to
  1981. perform drawing outside of the update event.  I bend that rule here.  I
  1982. could simply select this window and show it.  This would allow my normal
  1983. drawing and activating routines to be called.  The problem with that was,
  1984. I found that many times the status window appeared and then disappeared
  1985. before these update routines had a chance to draw the window.  This left
  1986. the user with a blank window that immediately went away.  So, I do the
  1987. activation and drawing right after showing it.
  1988.  
  1989. BUG NOTE: GetIndString will return a bogus string if the index is not
  1990. positive.
  1991. */
  1992.  
  1993. #pragma segment Main
  1994. void ShowStatusWindow(short messageID)
  1995. {
  1996.     Str255    msg;
  1997.  
  1998.     if (FailLowMemory(0)) {                            // running low on memory?
  1999.         KillSound();
  2000.         AlertUser(memFullErr, sLowMemory);
  2001.     }
  2002.     else {
  2003.         if (messageID > 0)
  2004.             GetIndString(msg, sMsgStrings, messageID);
  2005.         else
  2006.             msg[0] = 0;                                    // case there’s no message
  2007.         SetString(gStatusWindow->message, msg);
  2008.         ShowWindow((WindowPtr)gStatusWindow);            // show the window
  2009.         SelectWindow((WindowPtr)gStatusWindow);            // bring it to the front
  2010.         SetPort((WindowPtr)gStatusWindow);
  2011.         EraseRect(&(((WindowPtr)gStatusWindow)->portRect)); // erase old message
  2012.         HiliteControl((ControlHandle)((WindowPeek)gStatusWindow)->controlList, kControlNoPart);
  2013.         DrawStatusWindow();                                // draw the new message
  2014.         ValidRect(&(((WindowPtr)gStatusWindow)->portRect)); // avoid needless update
  2015.         gStatusWindow->showTime = TickCount();            // it’s show time folks
  2016.     }
  2017. }
  2018.  
  2019. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2020. /*
  2021. This initializes the status window, and keeps it hidden until the user
  2022. decides to play a sound.  I also center it for the first time, but the
  2023. user is free to drag it to a new location afterwards.  The status window
  2024. also has a message associated to it, so I allocate a string handle for this.
  2025. */
  2026.  
  2027. #pragma segment Initialize
  2028. void InitStatusWindow(void)
  2029. {
  2030.     WindowPtr        window;
  2031.     ControlHandle    stopButton;
  2032.  
  2033.     gStatusWindow = (StatWindowPeek)NewPtrClear(sizeof(StatusWindow));
  2034.     if (gStatusWindow == nil)
  2035.         EmergencyExit(sInitStatusErr);
  2036.     window = GetNewWindow(rStatusWindow, (Ptr)gStatusWindow, (WindowPtr)-1);
  2037.     if (window == nil)
  2038.         EmergencyExit(sInitStatusErr);
  2039.     SetWRefCon(window, rStatusWindow);
  2040.     stopButton = GetNewControl(rCancelCntl, window);
  2041.     if (stopButton == nil)
  2042.         EmergencyExit(sInitStatusErr);
  2043.     gStatusWindow->message = NewString("\p");    // a new empty string handle
  2044.     if (gStatusWindow->message == nil)
  2045.         EmergencyExit(sInitStatusErr);
  2046.     HNoPurge((Handle)gStatusWindow->message);
  2047. }
  2048.  
  2049. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2050. /*
  2051. I just flash the menubar for a moment instead of playing any sounds.  It’s
  2052. the same effect as setting the sound volume to zero but that would prevent
  2053. me playing my sounds.  Also, it helps to prevent the problem of _SysBeep
  2054. being called by the Dialog Manager while I’m playing a sound.  If my
  2055. application is playing a sound and, for example, the user clicks outside
  2056. of the Standard File dialog ModalDialog calls _SysBeep.  This can cause
  2057. the Mac to crash or trash my channel.
  2058.  
  2059. BUG NOTE: If the current Sound Manager were playing a sound and a
  2060. _SysBeep were to occur, bad things could happen on a Mac Plus/SE.  Either
  2061. the application’s channel would be trashed or the Mac could crash.
  2062.  
  2063. VERSION 1.1: The new Sound Manager will handle the problem presented in the
  2064. older Sound Manager regarding SysBeep.  If I'm running under the new Sound
  2065. Manager then I'll call SysBeep anyway.  The new Sound Manager will properly
  2066. handle the situation of an open sound channel when SysBeep is called.
  2067.  
  2068. VERSION 1.2: This is no longer needed since we only use Sound Manager 2 or later.
  2069. */
  2070.  
  2071. #pragma segment Main
  2072. pascal void DoErrorSound(short soundNo)
  2073. {
  2074.     unsigned long finalTicks;
  2075.  
  2076.     if (GetSoundMgrVersion() == 1) {
  2077.         if (soundNo > 0) {                        //only after the first time
  2078.             FlashMenuBar(0);
  2079.             Delay(kDelayTime, &finalTicks);
  2080.             FlashMenuBar(0);
  2081.         }
  2082.     }
  2083.     else
  2084.         SysBeep(30);                            //does the right thing now
  2085. }
  2086.  
  2087. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2088. /*
  2089. This tests if the volume has been set very low.  It’s a judgement call as
  2090. to what “too low” means.  The user sets the volume, so how could it be too
  2091. low? A setting of 0 could be considered too low, but in any case do not
  2092. adjust it.  I find the volume goes below 4 on a standard Mac, then there
  2093. is a perceivable difference.  I also wanted to show this routine as a
  2094. demonstration in how to handle such a situation.  Do not change it
  2095. directly! Ask the user to do it.  Consider the user that has their Mac
  2096. connected to a stack of Marshalls (which go to 11) and has purposely set
  2097. their Mac’s volume where they wanted it.  This may be 3 and if you crack
  2098. it up to 8, it could be a scene out of Back to the Future.
  2099.  
  2100. User Interface rule, let the user remain in control!
  2101.  
  2102. VERSION 1.2: Don't use GetSoundVol anymore. This just reads a low memory global
  2103. which is no longer valid with Sound Manager 3 or later. The old low global
  2104. is only 3 bits, which is why the range used to be 0-7. There are new machines
  2105. supported by Sound Manager 3 that have more than 8 volume level. So the
  2106. old global is scaled into the 0-7 range. You should avoid all of this non-sense
  2107. and start using the new calls of Sound Manager 3, and start using percentages.
  2108. */
  2109.  
  2110. #pragma segment Initialize
  2111. void CheckSoundVolume(void)
  2112. {
  2113.     Fixed    percent;
  2114.     long    soundVolume;
  2115.     short    curVolume;
  2116.     short    item;
  2117.     Str255    numStr;
  2118.  
  2119.     if (GetSoundMgrVersion() < 3)
  2120.     {
  2121.         // turn old 0-7 range into the new 0-0x0100 range
  2122.  
  2123.         curVolume = LMGetSdVolume();                // same as calling GetSoundVol()
  2124.         curVolume *= kFullVolume;
  2125.         curVolume += 7-1;                            // avoid rounding errors
  2126.         curVolume /= 7;                                // divid by old max
  2127.     }
  2128.     else
  2129.     {
  2130.         // get the current stereo levels and average them
  2131.  
  2132.         GetDefaultOutputVolume(&soundVolume);
  2133.         curVolume = (soundVolume >> 16) + (soundVolume & 0x0000FFFF);
  2134.         curVolume /= 2;
  2135.     }
  2136.  
  2137.     // take the current level and turn this in to a percentage of full volume,
  2138.     // then show the user that the level is low and how they may increase it.
  2139.  
  2140.     percent = FixDiv( (long)curVolume << 16, kFullVolume << 16);
  2141.     percent = FixMul(percent, 100L << 16);
  2142.     NumToString(percent >> 16, numStr);
  2143.     ParamText(numStr, "\p", "\p", "\p");        // show the current volume
  2144.     item = Alert(rSoundVolAlert, nil);
  2145. }
  2146.  
  2147. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2148. /*
  2149. Simply add all the buttons I want to use in the document window.  I get
  2150. the control templates, and add the control to the window.  I don’t check
  2151. for getting errors for two reasons.  I put these controls there.  If the
  2152. user removes them, it’s their problem.  If the application cannot get the
  2153. memory required for these, then the application is already out of memory
  2154. and checking here probably wouldn’t help much.  I do check before creating
  2155. the document that there was enough available memory.  I save the resource
  2156. ID into the control’s refCon so later I can tell which control was hit by
  2157. the user.
  2158.  
  2159. VERSION 1.1: Add the record button to the window.}
  2160. */
  2161.  
  2162. #pragma segment Open
  2163. void AddSndDocControls(WindowPtr window)
  2164. {
  2165.     ControlHandle    control;
  2166.  
  2167.     control = GetNewControl(rPlaySndCntl, window);
  2168.     if (control != nil)
  2169.         SetControlReference(control, rPlaySndCntl);
  2170.  
  2171.     control = GetNewControl(rHyperPlayCntl, window);
  2172.     if (control != nil)
  2173.         SetControlReference(control, rHyperPlayCntl);
  2174.  
  2175.     control = GetNewControl(rPlayScaleCntl, window);
  2176.     if (control != nil)
  2177.         SetControlReference(control, rPlayScaleCntl);
  2178.  
  2179.     control = GetNewControl(rMelodyCntl, window);
  2180.     if (control != nil)
  2181.         SetControlReference(control, rMelodyCntl);
  2182.  
  2183.     control = GetNewControl(rStopCntl, window);
  2184.     if (control != nil)
  2185.         SetControlReference(control, rStopCntl);
  2186.  
  2187.     control = GetNewControl(rRecordCntl, window);
  2188.     if (control != nil)
  2189.         SetControlReference(control, rRecordCntl);
  2190. }
  2191.  
  2192. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2193. #pragma segment Open
  2194. Boolean PositionAvailable(Point newPt, short wTitleHeight)
  2195. {
  2196.     WindowPtr oldWindow;
  2197.     Point delta;
  2198.     Point oldPt;
  2199.     Boolean taken;
  2200.  
  2201.     taken = false;
  2202.     oldWindow = FrontWindow();
  2203.     while ((oldWindow != nil) && !taken) {
  2204.         if (IsDocWindow(oldWindow) && ((WindowPeek)oldWindow)->visible) {
  2205.             oldPt = GetGlobalTopLeft(oldWindow);
  2206.             delta.v = AbsoluteValue(newPt.v - oldPt.v);
  2207.             delta.h = AbsoluteValue(newPt.h - oldPt.h);
  2208.             taken = (delta.h + delta.v)
  2209.                         <= ((kWindowPosStaggerH + kWindowPosStaggerV + wTitleHeight) / 2);
  2210.         }
  2211.         oldWindow = (WindowPtr)(((WindowPeek)oldWindow)->nextWindow);
  2212.     }
  2213.     return(!taken);
  2214. }
  2215.  
  2216. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2217. /*
  2218. There are a few approaches I thought of and tried, none of which satisfied
  2219. me.  ResEdit uses the simplest method, an offset from the front window.  I
  2220. don’t like this because it may cover up existing windows.  So my approach is
  2221. to go through the window list looking for an empty spot.  If the empty
  2222. spot causes the window to go off the screen, then I start a new stack off
  2223. to the right.  This will cause a new series of window to be stacked.  If the
  2224. new stack would cause the window to go off screen, then it’s time to give up.
  2225. All new windows will then be moved to the starting point and there is no
  2226. further stacking.  If I look at this routine too much, I get real tired.
  2227. If I try to change it at all, I get woozy trying to make it work again.
  2228.  
  2229. VERSION 1.2: System 7 provides for staggering windows, but it doesn't work
  2230. exactly the way I want it. Mine's better.
  2231. */
  2232.  
  2233. #pragma segment Open
  2234. WindowPtr NewStackedWindow(short windID, Ptr windStorage)
  2235. {
  2236.     Point windSize;
  2237.     Point newPt;
  2238.     WindowPtr newWindow;
  2239.     short wTitleHeight;
  2240.     short numStacks;
  2241.     Boolean taken;
  2242.  
  2243.     //set the initail starting point for a window, less the staggering amount
  2244.     newWindow = GetNewWindow(windID, windStorage, (WindowPtr)-1);
  2245.     windSize = BottomRight(newWindow->portRect);
  2246.     SubPt(TopLeft(newWindow->portRect), &windSize);
  2247.     wTitleHeight = GetWTitleHeight(GetWVariant(newWindow));
  2248.     SetPt(&newPt, kWindowPosStartPt - kWindowPosStaggerH, kWindowPosStartPt - kWindowPosStaggerV + GetMBarHeight());
  2249.  
  2250.     numStacks = 0;
  2251.     do { //add the staggering amount then test if the window goes off the screen
  2252.         taken = true;
  2253.         SetPt(&newPt, newPt.h + kWindowPosStaggerH, newPt.v + kWindowPosStaggerV + wTitleHeight);
  2254.         if (    ((newPt.v + windSize.v) > qd.screenBits.bounds.bottom)
  2255.              || ((newPt.h + windSize.h) > qd.screenBits.bounds.right))
  2256.         {
  2257.             numStacks++;
  2258.             SetPt(&newPt, kWindowPosStartPt + (numStacks * kWindowPosStaggerH),
  2259.                             kWindowPosStartPt + wTitleHeight + GetMBarHeight());
  2260.             if (((newPt.v + windSize.v) > qd.screenBits.bounds.bottom)
  2261.                         || ((newPt.h + windSize.h) > qd.screenBits.bounds.right)) {
  2262.                 SetPt(&newPt, kWindowPosStartPt, kWindowPosStartPt + wTitleHeight + GetMBarHeight());
  2263.                 taken = false;
  2264.             }
  2265.         }
  2266.     } while (taken && !(PositionAvailable(newPt, wTitleHeight)));
  2267.  
  2268.     MoveWindow(newWindow, newPt.h, newPt.v, true);
  2269.     return(newWindow);
  2270. }
  2271.  
  2272. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2273. /*
  2274. Create a new sound document and initialize all the data associated with
  2275. it.  If I encounter an error, then dispose of any memory allocated in the
  2276. attempt.  Allocate all necessary memory required for a sound document.  I
  2277. like to use NewPtrClear because is will initialize all the memory.  I
  2278. depend on real values or zero in my document fields.  Then its time to
  2279. build a sound document which contains all the controls and the list of
  2280. sounds.  I get the position for the list kept in a rectangle resource.
  2281. This  helps me to adjust the size of the list without changing code.  I
  2282. will make  an additional adjustment to the list’s height to insure better
  2283. scrolling.  This avoids the ugly white space of an improperly sized
  2284. rectangle.  If I cannot create the list, I’ll close the window and return
  2285. a NIL.  If I find after creating a new document that I’m low on memory,
  2286. I’ll close it and return an error.
  2287.  
  2288. SPECIAL NOTE: The Human Interface Group suggested that the buttons and the
  2289. list should in the System font.  I designed these windows using the
  2290. application font in 10 point.  If you change the call to TextFont, you
  2291. find that the buttons and the list will work properly in your font choice.
  2292.  
  2293. VERSION 1.1:  Size the window smaller to hide the record button from the
  2294. user if Sound Input is not available.  Added memory check to the beginning
  2295. of this routine before creating the document.  This was done because there
  2296. are two routines that call this one, OpenSoundDoc and NewSoundDoc which
  2297. both performed this check.  Having it here in one place reduces the chance of
  2298. future bugs (doing the same thing in two places) and reduces the size of
  2299. the code.
  2300. */
  2301.  
  2302. #pragma segment Open
  2303. OSErr CreateSoundDoc(short resRef, FSSpecPtr file)
  2304. {
  2305.     SndDocPeek newDocPtr;
  2306.     WindowPtr window;
  2307.     ListHandle list;
  2308.     RectHandle rHandle;
  2309.     Rect lView;
  2310.     Rect lBounds;
  2311.     Cell aCell;
  2312.     Point cSize;
  2313.     Point newSize;
  2314.     short maxListHeight;
  2315.     OSErr theErr;
  2316.     Boolean ignore;
  2317.  
  2318.     if (FailLowMemory(kMemForSndDoc)) {
  2319.         CloseResFile(resRef);                            //close it before leaving
  2320.         return(memFullErr);
  2321.     }
  2322.  
  2323.     theErr = noErr;
  2324.     newDocPtr = (SndDocPeek)NewPtrClear(sizeof(SndDocument));
  2325.     if (newDocPtr != nil) {
  2326.         window = NewStackedWindow(rSoundWindow, (Ptr)newDocPtr);
  2327.         SetPort(window);
  2328.         if (! HasSoundInput())
  2329.             SizeWindow(window, kSoundWindowSizeW,
  2330.                     kSoundWindowSizeH - (kStadardWhiteSpacing + kSndButtonSizeH), false);
  2331.         TextFont(0);                                    //set window to System font, blech
  2332.         AddSndDocControls(window);                        //add my buttons
  2333.         SetWRefCon((WindowPtr)newDocPtr, rSoundWindow); //mark as an app window
  2334.         SetWTitle((WindowPtr)newDocPtr, file->name);
  2335.         newDocPtr->resFile = resRef;                    //save its resource file ref
  2336.         newDocPtr->vRefNum = file->vRefNum;                //save its volume reference
  2337.         newDocPtr->dirID = file->parID;                    //save its directory ID
  2338.         newDocPtr->sndInUse = false;                    //not yet it doesn’t
  2339.         rHandle = (RectHandle)Get1Resource('RECT', rListRectID);
  2340.         if (rHandle != nil) {                            //get the stored list size
  2341.             lView = **rHandle;
  2342.             SetRect(&lBounds, 0, 0, 1, 0);                //one dimentional list
  2343.             SetPt(&cSize, 0, 0);                        //List Mgr will find cell size
  2344.             list = LNew(&lView, &lBounds, cSize, 0, window, false, false, false, true);
  2345.             maxListHeight = window->portRect.bottom - window->portRect.top - (2 * kStadardWhiteSpacing);
  2346.             if (maxListHeight < (lView.bottom - lView.top))
  2347.                 maxListHeight = (lView.bottom - lView.top);
  2348.             if (list != nil) {
  2349.                 newSize.h = (**list).cellSize.h;        //get the width of one cell
  2350.                 newSize.v = maxListHeight;                //get the best height for all cells
  2351.                 newSize.v -= maxListHeight % (**list).cellSize.v;
  2352.                 LSize(newSize.h, newSize.v, list);        //adjust for best scrolling
  2353.                 (**list).selFlags = lOnlyOne;            //single selections only
  2354.                 newDocPtr->list = list;                    //save the list handle
  2355.                 theErr = InitSndList(newDocPtr);        //initialize the list data
  2356.                 if (theErr == noErr) {
  2357.                     SetPt(&aCell, 0, 0);                //by default, I will...
  2358.                     LSetSelect(true, aCell, newDocPtr->list); //select first item
  2359.                     LSetDrawingMode(true, newDocPtr->list);
  2360.                     ShowWindow((WindowPtr)newDocPtr);    //get the show on the road
  2361.                     if (FailLowMemory(0))                //if I’m low on memory...
  2362.                         theErr = memFullErr;
  2363.                 }
  2364.             }
  2365.             else
  2366.                 theErr = nilHandleErr;                    //list handle was NIL
  2367.         }
  2368.         else
  2369.             theErr = nilHandleErr;                        //RECT handle was NIL
  2370.         if (theErr != noErr) {                            //could not create the list
  2371.             ignore = DoCloseWindow(window);                //if not, close the window
  2372.             newDocPtr = nil;                            //return nil pointer too
  2373.         }
  2374.     }
  2375.     else                                                //NewPtrClear was nil
  2376.         theErr = MemError();
  2377.     return(theErr);                                        //return the error, if any
  2378. }
  2379.  
  2380. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2381. /*
  2382. Believe it or not, but this turned out to be one of the more difficult
  2383. routines to write.  This was the best approach I could thing of to avoid
  2384. serious problems.  I don’t center the Standard File dialog because it
  2385. wouldn’t be under the File menu where the user probably has the mouse.  I
  2386. use OpenRFPerm because it allows for permissions and doesn’t depend on the
  2387. current directory.  First problem with opening a resource file was to
  2388. check if the file already being open.  Read Tech Notes #116 and #185.
  2389. GetFInfo seems to do the trick.  At least it does report all files that
  2390. are open on this machine.  It may be incorrect for files on AppleShare
  2391. opened by other machines.  What I’m worried about is when opening a
  2392. resource file for the second time on the same machine may return the
  2393. previous opener’s resource map.  This is very dangerous, and if the second
  2394. opener calls CloseResFile there will be a crash.  I want to be friendly
  2395. and if the user tries to open the file the second time and I’ve already
  2396. got it on the screen, then I’ll bring that window forward.  To test for
  2397. this, I compare the file’s name, DirID and vRefNum.  The vRefNum is
  2398. dynamic and needs to be converted into a volume name if I were to save
  2399. this information for future use.
  2400.  
  2401. There are a couple pitfalls, even with this method.  The user can open the
  2402. file, then move it to another directory.  This same thing confuses all
  2403. other applications I’ve tested.  Opening a resource file will allocate a
  2404. resource map handle into my heap, which may be large depending on the
  2405. number of resources in that file.  Additionally this loads all resources
  2406. marked “preload.”  So I set ResLoad to false to prevent the preloading.  I
  2407. test if the amount of memory I believe my document will require is
  2408. available after opening the resource file.  If true, I test if there are
  2409. any sound resources in that file and if not alert the user.  After all
  2410. this, create the new document.  If after creating the new document I find
  2411. that memory is too low, will close it and return an error.  If it does
  2412. fail, then close the file before anything else or there may not be enough
  2413. memory to show the alert.  All of these tests created a number of
  2414. IF-THEN-ELSE blocks and became unyielding.  C programmers get a break, so
  2415. gimme me one too.  I use the MPW Pascal EXIT.
  2416.  
  2417. BUG NOTE: Don’t open a resource file that is already open.  OpenResFile
  2418. may return an existing resource map when it gets opWrErr from the file
  2419. system.  If this happens, the resource file will not be unique and this
  2420. is very bad.  Another problem is if I get a read-only path and someone
  2421. else opens it for read/write.  This is also very bad.  Read Tech Notes
  2422. #116 and #185 hint at this problem, but I think a more comprehensive one
  2423. is in order.
  2424.  
  2425. BUG NOTE: GetWDInfo fails with nsvErr if the working directory returned
  2426. from Standard File is the root of an A/UX volume.  I could work around
  2427. this,  but it would be dependant on the current version of A/UX.  Read
  2428. Tech Note #229.  I believe this is also true for TOPS.
  2429.  
  2430. VERSION 1.1:  I'll open files that do not have snd resources in them.
  2431. This allows users to open existing files and then record or paste a sound
  2432. into it.  I changed OpenRFPerm to HOpenResFile to avoid working
  2433. directories and to be consistent with the rest of the sources.  I
  2434. separated the standard file code from OpenSndDoc to support opening
  2435. documents being open from the Finder.  This allows me to share the same
  2436. routine to open files either from double clicking them in the Finder, or
  2437. by the Standard File dialog.  Removed the checking for low memory conditions
  2438. since CreateSoundDoc is now doing this.
  2439. */
  2440.  
  2441. #pragma segment Open
  2442. void OpenSoundDoc(FSSpecPtr file)
  2443. {
  2444.     HParamBlockRec fPBRec;
  2445.     WindowPtr window;
  2446.     short resFileRef;
  2447.     OSErr theErr;
  2448.  
  2449.     fPBRec.fileParam.ioCompletion = nil;            //prepare a paramBlock
  2450.     fPBRec.fileParam.ioNamePtr = file->name;
  2451.     fPBRec.fileParam.ioVRefNum = file->vRefNum;
  2452.     fPBRec.fileParam.ioDirID = file->parID;
  2453.     fPBRec.fileParam.ioFVersNum = 0;
  2454.     fPBRec.fileParam.ioFDirIndex = 0;
  2455.     theErr = PBHGetFInfoSync(&fPBRec);                 //fPBRec on stack, synch only
  2456.     if (theErr == noErr) {
  2457.         if (fPBRec.fileParam.ioFlAttrib & kResForkOpenBit) {
  2458.             if (OpenByApp(file, &window))
  2459.                 SelectWindow(window);                //I opened this one, select it
  2460.             else
  2461.                 AlertUser(noErr, sCurInUseErr);        //in use by someone else
  2462.             return;
  2463.         }
  2464.     } else {
  2465.         AlertUser(theErr, sStandardErr);            //PBGetFInfo failed
  2466.         return;
  2467.     }
  2468.     SetResLoad(false);                                //don’t load any resources
  2469.     resFileRef = FSpOpenResFile(file, fsCurPerm);
  2470.     theErr = ResError();                            //save error, if any
  2471.     SetResLoad(true);                                //restore ResLoad state
  2472.     UseResFile(gAppResRef);                            //changes ResErr
  2473.     if (resFileRef != kResFileNotOpened)            //error from OpenRFPerm?
  2474.         theErr = CreateSoundDoc(resFileRef, file);
  2475.     if (theErr != noErr)
  2476.         AlertUser(theErr, sNewDocErr);                 //couldn’t create new doc
  2477. }
  2478.  
  2479. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2480. /*
  2481. VERSION 1.1:  Create a new file for the user.  I prefer to use the new
  2482. HCreateResFile to avoid working directories, and to be consistent with
  2483. the rest of the sources.  Also, I need the real vRefNum and dirID to
  2484. store in the sndDoc record.  After creating the file, I set its Finder
  2485. information to the proper type and creator.  Finally, I get to open the
  2486. new file.  After this point everything is exactly like opening an
  2487. existing file and creating a new sound document.
  2488.  
  2489. VERSION 1.2: If dupFNErr is returned by HCreateResFile, then the user
  2490. wants to replace the file with a new SoundApp document.
  2491. */
  2492.  
  2493. #pragma segment Open
  2494. void NewSoundDoc(void)
  2495. {
  2496.     Str255 msg;
  2497.     StandardFileReply reply;
  2498.     StringHandle strHandle;
  2499.     short resFileRef;
  2500.     OSErr theErr;
  2501.  
  2502.     strHandle = (StringHandle)Get1Resource('STR ', rPutFileMsg);
  2503.     if (strHandle != nil)
  2504.         PStringCopy(*strHandle, msg);                        //save no name title
  2505.     else
  2506.         msg[0] = 0;                                            //at least an empty string
  2507.  
  2508.     StandardPutFile(msg, "\p", &reply);
  2509.     if (reply.sfGood)
  2510.     {
  2511.         theErr = noErr;
  2512.         if (reply.sfReplacing)
  2513.             theErr = FSpDelete(&reply.sfFile);                //we're replacing it
  2514.         if (theErr == noErr)
  2515.         {
  2516.             FSpCreateResFile(&reply.sfFile, rAppSignature, rSndAppDocType, reply.sfScript);
  2517.             theErr = ResError();
  2518.             if (theErr == noErr) {
  2519.                 resFileRef = FSpOpenResFile(&reply.sfFile, fsCurPerm);
  2520.                 theErr = ResError();                        //save error, if any
  2521.                 UseResFile(gAppResRef);                        //changes ResErr
  2522.                 if (resFileRef != kResFileNotOpened)        //error from HOpenResFile
  2523.                     theErr = CreateSoundDoc(resFileRef, &reply.sfFile);
  2524.             }
  2525.         }
  2526.         if (theErr != noErr)
  2527.             AlertUser(theErr, sNewDocErr);                         //return the error
  2528.     }
  2529. }
  2530.  
  2531. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2532. /*
  2533. This is much more than what a typical file filter might do but I wanted
  2534. the user to easily find files that contained snd resources.  So, the
  2535. global flag gSndFilesOnly is used to determine when to filter for such
  2536. files.  Otherwise, I show all files and allow the application to report to
  2537. the user the file they’ve just tried to open doesn’t have any sounds to
  2538. play with.  Opening resource forks can be tricky if it’s already open.  It
  2539. would be very bad to use a resource fork that is already open by another
  2540. application.  The problem being that the Resource Manager doesn’t deal
  2541. with multiple users.  Read Tech notes #116 and #185.  There’s also another
  2542. problem.  If a resource fork is opened by two applications and one closes
  2543. the file then the entire resource fork may closed out from underneath the
  2544. other application.  I do, however, want to show the user files that
  2545. contain sound resources even if they are currently open.  I use
  2546. HOpenResFile with read only permission, which will give me a unique
  2547. resource reference.  I look for a 'snd ' resource and then immediately
  2548. close the file.  Do not use a resource file opened with read only
  2549. permission.  Another reason to use HOpenResFile  is to avoid a necessary
  2550. working directory.  I do not have one while in the file filter, but can
  2551. use the DirID.  Performing this search on each file is time consuming so I
  2552. show a spinning cursor to show the user I’m working.   Opening a resource
  2553. fork may load resources mark preload.   To avoid this, I call SetResLoad
  2554. to false.  I bet you thought the Resource Manager was a free lunch.  Ha!
  2555. Read Tech Note #203 for other reasons not to play with resources.
  2556.  
  2557. BUG NOTE: While debugging this routine using heap scramble, I found that
  2558. OpenResFile would not open the requested file.  I’m not sure if this is a
  2559. problem with OpenResFile or SFGetFile.
  2560.  
  2561. VERSION 1.1: The bug mentioned above was found.  The problem is that the
  2562. paramBlock happens to be a re-locatable block in the heap.  Passing the
  2563. de-reference ioNamePtr to HOpenResFile was de-referencing this
  2564. re-locatable paramBlock.  Since HOpenResFile moves memory, the namePtr
  2565. would no longer valid and thus HOpenResFile would fail.  Now I copy the
  2566. name out of the paramBlock and use the local variable in HOpenResFile.
  2567. This problem was fixed in System 7, which no longer passes a re-locatable
  2568. block to the file filter.  The new version allows for any resource file
  2569. to be opened.  Because of this new feature, I only show the user files
  2570. that have a resource fork.
  2571.  
  2572. VERSION 1.2: This is a filter for System 7 now, and I don't show invisible files.
  2573. */
  2574.  
  2575. #pragma segment Open
  2576. pascal Boolean SFFilter(CInfoPBPtr p, Boolean *sndFilesOnly)
  2577. {
  2578. #define kShowIt            false                //false means I do not filter out...
  2579. #define kDoNotShowIt    true                //the file and true means that I do.
  2580.  
  2581.     long oldTicks;
  2582.     short resRef;
  2583.     short curRes;
  2584.     Boolean result;
  2585.  
  2586.     oldTicks = TickCount();
  2587.     result = kDoNotShowIt;                    //don’t show anything until I say so
  2588.  
  2589.     if ( (*sndFilesOnly) && !(p->hFileInfo.ioFlFndrInfo.fdFlags & fInvisible) )
  2590.     {
  2591.         curRes = CurResFile();
  2592.         SetResLoad(false);
  2593.         resRef = HOpenResFile(p->hFileInfo.ioVRefNum, p->hFileInfo.ioFlParID,
  2594.                                 p->hFileInfo.ioNamePtr, fsRdPerm);
  2595.         if (resRef != kResFileNotOpened) {
  2596.             UseResFile(resRef);
  2597.             if (Count1Resources(soundListRsrc) > 0)
  2598.                 result = kShowIt;            //hey, we found a sound in here
  2599.             CloseResFile(resRef);
  2600.         }                                    //restore everything
  2601.         SetResLoad(true);
  2602.         UseResFile(curRes);
  2603.     } else
  2604.     {
  2605.         if (   !(p->hFileInfo.ioFlFndrInfo.fdFlags & fInvisible)    // if not invisible
  2606.              && (p->hFileInfo.ioFlRLgLen > 0) )                        // and has resources
  2607.         {
  2608.             result = kShowIt;
  2609.         }
  2610.     }
  2611.     //RotateCursor(TickCount() - oldTicks);
  2612.     return(result);
  2613. }
  2614.  
  2615. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2616. #pragma segment Open
  2617. pascal short SFGetHook(short mySFItem, DialogPtr dialog, void *sndFilesOnly)
  2618. {
  2619.     ControlHandle cntl;
  2620.     Rect r;
  2621.     short kind;
  2622.     short result;
  2623.  
  2624.     result = mySFItem;
  2625.     GetDialogItem(dialog, rSndOnlyCheckBox, &kind, (Handle *)&cntl, &r);
  2626.     switch (mySFItem) {
  2627.  
  2628.         case sfHookFirstCall:
  2629.             if (*(Boolean *)sndFilesOnly)
  2630.                 SetControlValue(cntl, kCntlOn);
  2631.             else
  2632.                 SetControlValue(cntl, kCntlOff);
  2633.             break;
  2634.  
  2635.         case rSndOnlyCheckBox:
  2636.             if (GetControlValue(cntl) == kCntlOff) {
  2637.                 SetControlValue(cntl, kCntlOn);
  2638.                 *(Boolean *)sndFilesOnly = true;
  2639.             }
  2640.             else {
  2641.                 SetControlValue(cntl, kCntlOff);
  2642.                 *(Boolean *)sndFilesOnly = false;
  2643.             }
  2644.             result = sfHookRebuildList;
  2645.             break;
  2646.  
  2647.     }
  2648.     return (result);
  2649. }
  2650.  
  2651. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2652. /*
  2653. VERSION 1.1: This routine used to be inside of OpenSoundDoc.  The
  2654. standard file code was removed to here in order to support opening
  2655. documents being open from the Finder.  I've switched to using a constant
  2656. for the topLeft point of the Standard File dialog.  It saves a few bytes
  2657. of code, so what the hell?  I found a cosmetic problem with the cursor
  2658. not being restored back to arrow after returning Standard File if there
  2659. was an error dialog shown immediately.  So, it is immediately set back to
  2660. the arrow.
  2661. */
  2662.  
  2663. #pragma segment Main
  2664. void GetSoundDoc(void)
  2665. {
  2666.     StandardFileReply reply;
  2667.     SFTypeList typeList;                            //not used, just a placeholder
  2668.     Point sfTopLeft;
  2669.     Boolean sndFilesOnly;
  2670.  
  2671.     //SpinCursor(0);                                    //get the spinning cursor ready
  2672.     sfTopLeft.v = -1;                                //-1,-1 means to center the dialog
  2673.     sfTopLeft.h = -1;
  2674.     sndFilesOnly = false;
  2675.     CustomGetFile((FileFilterYDUPP)GetRoutineAddress(SFFilter), -1, typeList, &reply, rCustomGetFileDLOG,
  2676.             sfTopLeft, GetRoutineAddress(SFGetHook), nil, nil, nil, &sndFilesOnly);
  2677.     SetCursor(&qd.arrow);
  2678.     if (reply.sfGood)
  2679.         OpenSoundDoc(&reply.sfFile);
  2680. }
  2681.  
  2682. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2683. /*
  2684. Draw the contents of the about window in response to an update event.  At
  2685. this point, BeginUpdate has been called which sets the window’s visRgn to
  2686. clip drawing only where it needs to be done.  I have some text to draw, an
  2687. icon, a picture, and a default button with its outline.  If I have a color
  2688. icon handle I’ll call PlotCIcon.  I offset the picture to draw to the
  2689. right of the icon.  The text will appear in a rectangle as large as the
  2690. window, but below the icon and above the button.  This allows me the
  2691. change the text and if needed change the size of the window’s rectangle to
  2692. compensate.  I won’t have to recompile any code.  Some people use dialogs
  2693. because of this, but I’m demonstrating how it can be done without them.  I
  2694. use UpdateControls to avoid needless drawing that happens with DrawControls.
  2695. It not only runs faster but doesn’t flicker.
  2696.  
  2697. VERSION 1.2: Uses System 7's PlotIcon to draw the proper icon.
  2698. */
  2699.  
  2700. #pragma segment Main
  2701. void DrawAboutWindow(WindowPtr window)
  2702. {
  2703.     Rect theRect;
  2704.     OSErr ignoreErr;
  2705.  
  2706.     PenNormal();
  2707.     SetRect(&theRect, kStdAlertIconLeft, kStdAlertIconTop, kStdAlertIconRight, kStdAlertIconBottom);
  2708.     ignoreErr = PlotIconID(&theRect, atNone, ttNone, rMoofIcon);
  2709.  
  2710.     theRect = (**(PicHandle)((AboutWPeek)window)->appPict).picFrame;
  2711.     OffsetRect(&theRect, -theRect.left + kStdAlertIconRight + kStadardWhiteSpacing,
  2712.                             -theRect.top + kStdAlertIconTop);
  2713.     DrawPicture((PicHandle)((AboutWPeek)window)->appPict, &theRect);
  2714.  
  2715.     SetRect(&theRect, window->portRect.left, kStdAlertIconBottom,
  2716.                 window->portRect.right,
  2717.                 window->portRect.bottom - kDafaultButSizeH);
  2718.     InsetRect(&theRect, kStadardWhiteSpacing, kStadardWhiteSpacing);
  2719.     HLock(((AboutWPeek)window)->comment);
  2720.     TETextBox(*(((AboutWPeek)window)->comment) + 1,
  2721.                 StrLength(*(((AboutWPeek)window)->comment)), &theRect, teJustLeft);
  2722.     HUnlock(((AboutWPeek)window)->comment);
  2723.  
  2724.     UpdateControls(window, window->visRgn);
  2725.     DoButtonOutline((ControlHandle)((WindowPeek)window)->controlList);
  2726. }
  2727.  
  2728. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2729. /*
  2730. First thing to do is call KillSound to stop any sound in progress and
  2731. close the status window.  If there’s enough memory available, I’ll play
  2732. the about sound.  This is sound is asynchronous and will automatically be
  2733. disposed of when completed.  There is an icon, taken from the bundle
  2734. resources, and a picture.  The text is taken from a string resource.  It
  2735. contains a couple variables just like ParamText would want.  I get the
  2736. current name of the application from the AppParms.  This is the name of
  2737. the application as specified by the user.  I read in my 'vers' resource
  2738. to get the current version to be displayed in the window.  Read Tech Note
  2739. 189 for more details on the vers resource.  I think these are two
  2740. important things to show in the about box.  These two portions of the text
  2741. are put into place with my own version of ParamText.   I tried all of this
  2742. with a standard dialog, but had trouble.  Sometimes the color icon didn’t
  2743. show up.  Trying to center justify text with a statText item wasn’t really
  2744. possible.  On the Mac SE, for some unknown reason, TESetJust failed to
  2745. center the textH of the dialog.  I also found that this call would set the
  2746. dialog’s text back to Chicago even after I had called TextFont.  So, I
  2747. gave up and did everything myself.  This is a demonstration of how to
  2748. create a dialog without using the Dialog Manager.
  2749. */
  2750.  
  2751. #pragma segment Main
  2752. void DoAbout(void)
  2753. {
  2754.     Str255            verNum;
  2755.     Str255            appName;
  2756.     Ptr                aboutPtr;
  2757.     AboutWPeek        aboutPeek;
  2758.     ControlHandle    control;
  2759.     VersRecHndl        curVersion;
  2760.     OSErr            theErr;
  2761.     Boolean            ignore;
  2762.  
  2763.     KillSound();
  2764.     aboutPtr = NewPtrClear(sizeof(AboutWindow));
  2765.     if (aboutPtr != nil) {
  2766.         aboutPeek = (AboutWPeek)GetNewWindow(rAboutWindow, aboutPtr, (WindowPtr)-1);
  2767.         SetWRefCon((WindowPtr)aboutPeek, rAboutWindow);
  2768.         curVersion = (VersRecHndl)Get1Resource('vers', 1);
  2769.         if (curVersion != nil)
  2770.             PStringCopy((**curVersion).shortVersion, verNum); // get version string
  2771.         else
  2772.             verNum[0] = 0;                                // at least initialize it
  2773.         PStringCopy(LMGetCurApName(), appName);
  2774.         aboutPeek->appPict = Get1Resource('PICT', rAppPict);
  2775.         aboutPeek->comment = Get1Resource('STR ', rAboutText);
  2776.         control = GetNewControl(rAboutOkCntl, (WindowPtr)aboutPeek);
  2777.  
  2778.         if (     (aboutPeek->appPict != nil)
  2779.              && (aboutPeek->comment != nil)
  2780.              && (control != nil))
  2781.         {
  2782.             HNoPurge(aboutPeek->appPict);                // must keep them around
  2783.             HNoPurge(aboutPeek->comment);
  2784.             MyParamText((StringHandle)aboutPeek->comment, appName, verNum);
  2785.             if (!FailLowMemory(0))
  2786.                 theErr = AsynchSndPlay((SndListHandle)Get1Resource(soundListRsrc, rMoofSound));
  2787.         }
  2788.         else                                            // couldn’t build window
  2789.             ignore = DoCloseWindow((WindowPtr)aboutPeek);
  2790.     }
  2791. }
  2792.  
  2793. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2794. /*
  2795. Get the selected sound and pass it to AsynchSndPlay or HyperSndPlay.  This
  2796. depends on the normal flag.  HyperCard’s method is not normal.  This is
  2797. the HyperCard version of playing a sound.  It resamples any sound to
  2798. middle C.  If the resource is too large to fit in memory, I’ll get a nil
  2799. handle error from the SoundUnit.  It might be nice to test for this
  2800. before calling the SoundUnit and telling the user they’re too low on
  2801. memory, but the SoundUnit is robust enough and reports the error.  It’s
  2802. important to call KillSound to dispose of any data that was
  2803. allocated if an error were to occur.
  2804. */
  2805.  
  2806. #pragma segment Main
  2807. void PlaySelectedSnd(SndDocPeek sndDoc, short message)
  2808. {
  2809.     SndListHandle    sndHandle;
  2810.     OSErr            theErr;
  2811.  
  2812.     theErr = GetSelection(sndDoc, &sndHandle);
  2813.     if (theErr == noErr) {
  2814.         if (message == sPlayingMsg)
  2815.             theErr = AsynchSndPlay(sndHandle);
  2816.         else
  2817.             theErr = HyperSndPlay(sndHandle);
  2818.     }
  2819.     if (theErr == noErr) {
  2820.         sndDoc->sndInUse = true;                // this document has a snd in use
  2821.         ShowStatusWindow(message);
  2822.     }
  2823.     else {
  2824.         KillSound();
  2825.         AlertUser(theErr, sSoundErr);
  2826.     }
  2827. }
  2828.  
  2829. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2830. /*
  2831. Given a sound resource ID, this will get my song resource and call the
  2832. SoundUnit to use that sampled sound and song to play a tune.  This
  2833. application will play one of two songs for sampled sounds.  If any error
  2834. is encountered, I call KillSound to dispose of all data.
  2835. */
  2836.  
  2837. #pragma segment Main
  2838. void PlaySndSong(SndDocPeek sndDoc, short sndID)
  2839. {
  2840.     SndChannelPtr    chan;
  2841.     SndListHandle    sndInst;
  2842.     SndListHandle    sndSong;
  2843.     OSErr            theErr;
  2844.  
  2845.     theErr = GetSelection(sndDoc, &sndInst);
  2846.     if (theErr == noErr) {
  2847.         sndSong = (SndListHandle)Get1Resource(soundListRsrc, sndID);
  2848.         theErr = ResError();                        // save any error
  2849.         if (sndSong != nil) {
  2850.             theErr = GetSampleChan(&chan, kInitNone, sndInst);
  2851.             if (theErr == noErr) {
  2852.                 sndDoc->sndInUse = true;            // this document has a snd in use
  2853.                 theErr = PlaySong(chan, sndSong);
  2854.             }
  2855.         }
  2856.     }
  2857.     if (theErr == noErr) {
  2858.         if (sndID == rScaleSnd)
  2859.             ShowStatusWindow(sScaleMsg);
  2860.         else                                        // I can play scales or a melody
  2861.             ShowStatusWindow(sMelodyMsg);
  2862.     }
  2863.     else {                                            // catch any errors
  2864.         KillSound();
  2865.         AlertUser(theErr, sSoundErr);
  2866.     }
  2867. }
  2868.  
  2869. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2870. /*
  2871. Given a sound resource ID, this will get my song resource and call the
  2872. SoundUnit to use the note synthesizer and song to play a tune.  I request
  2873. the note channel’s timbre (sounds like “tom burr”).  If any error is
  2874. encountered, I call KillSound to dispose of all data.
  2875. */
  2876.  
  2877. #pragma segment Main
  2878. void PlaySquareSong(short sndID)
  2879. {
  2880.  
  2881.     SndListHandle    sndSong;
  2882.     SndChannelPtr    chan;
  2883.     OSErr            theErr;
  2884.  
  2885.     sndSong = (SndListHandle)Get1Resource(soundListRsrc, sndID);
  2886.     if (sndSong != nil) {
  2887.         theErr = GetSquareWaveChan(&chan, kPreferredTimbre);
  2888.         if (theErr == noErr) {
  2889.             theErr = PlaySong(chan, sndSong);
  2890.             if (theErr == noErr) {
  2891.                 if (sndID == rScaleSnd)
  2892.                     ShowStatusWindow(sScaleMsg);
  2893.                 else                                // I play scales or a melody
  2894.                     ShowStatusWindow(sMelodyMsg);
  2895.             }
  2896.         }
  2897.         if (theErr != noErr) {                        // catch any errors
  2898.             KillSound();
  2899.             AlertUser(theErr, sSoundErr);
  2900.         }
  2901.     }
  2902.     else
  2903.         AlertUser(ResError(), sResErr);                // I’ll return the resource error
  2904. }
  2905.  
  2906. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2907. /*
  2908. This is a demonstration of the note synth’s tone qualities (or the lack
  2909. there of).  This simply loops through timbres sending alternating note and
  2910. rest commands.  Once all the notes have been sent, then I need to send a
  2911. callBackCmd to signal the SoundUnit to dispose of the channel.  Well,
  2912. actually the SoundUnit will set a global flag that the application will be
  2913. polling for later in the event loop.  Once this happens, or if any errors
  2914. are encountered along the way, KillSound will be called.  One very
  2915. disappointing aspect to changing the timbre is that the Mac Plus or SE
  2916. cannot handle this while a note is sounding.  The Apple Sound Chip can and
  2917. if you wanted to remove the rests try this routine on a Mac II, for
  2918. example, you can hear a continuous note while the timbre changes.  Try
  2919. this on a Mac Plus and you’ll hear garbage.  I’d show this myself, but how
  2920. do I determine if the Mac has the ASC?
  2921.  
  2922. BUG NOTE: There is problem when the final sound command is a freqDurationCmd.
  2923. The note will continue to sound, looping forever, until a quietCmd is sent
  2924. or the channel is disposed of.  To prevent unwanted looping, I send a
  2925. quietCmd after all notes.
  2926. */
  2927.  
  2928. #pragma segment Main
  2929. void PlaySquareTimbres(void)
  2930. {
  2931.     SndChannelPtr    chan;
  2932.     short            timbre;
  2933.     OSErr            theErr;
  2934.  
  2935.     theErr = GetSquareWaveChan(&chan, kPreferredTimbre);
  2936.     if (theErr == noErr) {
  2937.         ShowStatusWindow(sTimbresMsg);
  2938.         for (timbre = kSineWave; timbre <= kSquareWave; timbre += 8) {
  2939.             theErr = SetSquareWaveTimbre(chan, timbre, kWait);
  2940.             if (theErr == noErr)
  2941.                 theErr = SendNote(chan, kOneSecond / 2, kOctave7 + Akey);
  2942.             if (theErr == noErr)
  2943.                 theErr = SendRest(chan, kOneSecond / 10);
  2944.             timbre = timbre + 8;                    // skip a few more timbres
  2945.             if (theErr != noErr)                    // if there was an error...
  2946.                 break;                                // get out of the loop
  2947.         }
  2948.     }
  2949.     if (theErr == noErr)
  2950.         theErr = SoundComplete(chan);
  2951.     else {                                            // catch any errors
  2952.         KillSound();
  2953.         AlertUser(theErr, sSoundErr);
  2954.     }
  2955. }
  2956.  
  2957. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2958. /*
  2959. This demonstrates the wave table synthesizers.  First thing to do is
  2960. obtain a wave cycle and the 'snd ' resource containing a song to be
  2961. played.  Then I’m ready to get the four wave channels and install the
  2962. chosen wave.  Once the wave is installed into the channel I can dispose of
  2963. the memory used to create the wave, since the Sound Manager will copy it
  2964. to its internal buffers.  At this point I’m ready to play the song.  It’s
  2965. not easy to hear four wave synths playing the same note with the same wave
  2966. table.  I was going to add a modifier to the channel that would transpose
  2967. each channels note, but I found a bug.
  2968.  
  2969. BUG NOTE: Installing a modifier to one of the wave table channels caused
  2970. the channel to fail.  My normal sequence of events is this: I synchronize
  2971. the four channels, send all the note commands, end this with the
  2972. callBackCmd, and finally release the channels to play their queues.  When
  2973. I added a modifier, the callBackCmd was the first command to be processed.
  2974. This caused my completion routines to be called and before the channel
  2975. made any sound it was disposed.  I tried this without the callBackCmd and
  2976. the channel never processed any commands.
  2977.  
  2978. BUG NOTE: The wave table synthesizer is not working on a non-Apple Sound
  2979. chip based Mac.  At least not so far with any System 6.0x releases.  This
  2980. leaves the Mac Plus/SE without four tone polyphonic sound.
  2981.  
  2982. VERSION 1.2: No longer need to call HasWorkingWaveTables since Sound Manager
  2983. 2 and later fixed the problem.
  2984. */
  2985.  
  2986. #pragma segment Main
  2987. void PlayWaveScale(void)
  2988. {
  2989.     SndChannelPtr    chan1, chan2, chan3, chan4;
  2990.     SndListHandle    sndSong;
  2991.     SndListHandle    waveHandle;
  2992.     Ptr                waveTablePtr;
  2993.     long            offSet;
  2994.     short            sndType;
  2995.     short            waveLength;
  2996.     OSErr            theErr;
  2997.  
  2998.     sndSong = (SndListHandle)Get1Resource(soundListRsrc, rScaleSnd);
  2999.     if (sndSong != nil) {
  3000.         waveHandle = (SndListHandle)Get1Resource(soundListRsrc, rTenorVox);
  3001.         theErr = HoldSnd(waveHandle);
  3002.         if (theErr == noErr) {
  3003.             offSet = GetSndDataOffset(waveHandle, &sndType, &waveLength);
  3004.             waveTablePtr = (Ptr)((long)*waveHandle + offSet);
  3005.             theErr = GetWaveChans(&chan1, &chan2, &chan3, &chan4);
  3006.             if (theErr == noErr) {
  3007.                 theErr = InstallWave(chan1, waveTablePtr, waveLength);
  3008.                 if (theErr == noErr) {
  3009.                     theErr = InstallWave(chan2, waveTablePtr, waveLength);
  3010.                     if (theErr == noErr) {
  3011.                         theErr = InstallWave(chan3, waveTablePtr, waveLength);
  3012.                         if (theErr == noErr)
  3013.                             theErr = InstallWave(chan4, waveTablePtr, waveLength);
  3014.                     }
  3015.                 }
  3016.             }
  3017.             HUnlock((Handle)waveHandle);
  3018.             HPurge((Handle)waveHandle);
  3019.             if (theErr == noErr)
  3020.                 theErr = Play4ChanSongs(chan1, chan2, chan3, chan4,
  3021.                                         sndSong, sndSong, sndSong, sndSong);
  3022.             if (theErr == noErr)
  3023.                 ShowStatusWindow(sScaleMsg);
  3024.             else {                                // catch any SoundUnit errors
  3025.                 KillSound();
  3026.                 AlertUser(theErr, sSoundErr);
  3027.             }
  3028.         }
  3029.         else
  3030.             AlertUser(theErr, sResErr);            // couldn’t get waveHandle
  3031.     }
  3032.     else
  3033.         AlertUser(ResError(), sResErr);            // couldn’t get song
  3034. }
  3035.  
  3036. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3037. /*
  3038. This is a utility routine used to obtain the four snd resources that
  3039. contain parts of a song.  Nothing much to do other then get the resource
  3040. and do error checking.
  3041. */
  3042.  
  3043. #pragma segment Main
  3044. OSErr GetSndSongs(short sndSongID1, short sndSongID2,
  3045.                     short sndSongID3, short sndSongID4,
  3046.                     SndListHandle *sndSong1, SndListHandle *sndSong2,
  3047.                     SndListHandle *sndSong3, SndListHandle *sndSong4)
  3048. {
  3049.     OSErr    result = noErr;                            // initialize result
  3050.  
  3051.     // get all the snds
  3052.     *sndSong1 = (SndListHandle)Get1Resource(soundListRsrc, sndSongID1);
  3053.     if (sndSong1 != nil) {
  3054.         *sndSong2 = (SndListHandle)Get1Resource(soundListRsrc, sndSongID2);
  3055.         if (sndSong2 != nil) {
  3056.             *sndSong3 = (SndListHandle)Get1Resource(soundListRsrc, sndSongID3);
  3057.             if (sndSong3 != nil)
  3058.                 *sndSong4 = (SndListHandle)Get1Resource(soundListRsrc, sndSongID4);
  3059.         }
  3060.     }
  3061.     if ((sndSong1 == nil) || (sndSong2 == nil)
  3062.      || (sndSong3 == nil) || (sndSong4 == nil))
  3063.         result = ResError();                        // return resource error
  3064.     return (result);
  3065. }
  3066.  
  3067. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3068. /*
  3069. This routine is a utility I’m using to prepare four wave table channels.
  3070. First thing to do is obtain a wave table data I stored in a set of 'snd '
  3071. resources.  Then I’m ready to install these wave tables into the four wave
  3072. channels.  Once the waves are installed into the channel I can dispose of
  3073. the memory used to create each wave, since the Sound Manager will copy
  3074. them to its internal buffers.  At this point the channels are ready to
  3075. play sounds.
  3076. */
  3077.  
  3078. #pragma segment Main
  3079. OSErr InstallWaveSnds(SndChannelPtr chan1, SndChannelPtr chan2,
  3080.                       SndChannelPtr chan3, SndChannelPtr chan4,
  3081.                       short waveID1, short waveID2, short waveID3, short waveID4)
  3082. {
  3083.     SndListHandle    waveSnd1, waveSnd2, waveSnd3, waveSnd4;
  3084.     Ptr                wavePtr;
  3085.     long            offSet;
  3086.     short            waveLgth;
  3087.     short            sndType;
  3088.     OSErr            theErr;
  3089.  
  3090.     // get em and hold em down
  3091.     waveSnd1 = (SndListHandle)Get1Resource(soundListRsrc, waveID1);
  3092.     theErr = HoldSnd(waveSnd1);
  3093.     if (theErr == noErr) {
  3094.         waveSnd2 = (SndListHandle)Get1Resource(soundListRsrc, waveID2);
  3095.         theErr = HoldSnd(waveSnd2);
  3096.         if (theErr == noErr) {
  3097.             waveSnd3 = (SndListHandle)Get1Resource(soundListRsrc, waveID3);
  3098.             theErr = HoldSnd(waveSnd3);
  3099.             if (theErr == noErr) {
  3100.                 waveSnd4 = (SndListHandle)Get1Resource(soundListRsrc, waveID4);
  3101.                 theErr = HoldSnd(waveSnd4);
  3102.             }
  3103.         }
  3104.     }
  3105.     if (theErr != noErr)
  3106.         return (theErr);                            // we’re out of here
  3107.                                                     // catch the waves
  3108.     offSet = GetSndDataOffset(waveSnd1, &sndType, &waveLgth);
  3109.     wavePtr = (Ptr)((long)*waveSnd1 + offSet);
  3110.     theErr = InstallWave(chan1, wavePtr, waveLgth);
  3111.     if (theErr == noErr) {
  3112.         offSet = GetSndDataOffset(waveSnd2, &sndType, &waveLgth);
  3113.         wavePtr = (Ptr)((long)*waveSnd1 + offSet);
  3114.         theErr = InstallWave(chan2, wavePtr, waveLgth);
  3115.         if (theErr == noErr) {
  3116.             offSet = GetSndDataOffset(waveSnd3, &sndType, &waveLgth);
  3117.             wavePtr = (Ptr)((long)*waveSnd1 + offSet);
  3118.             theErr = InstallWave(chan3, wavePtr, waveLgth);
  3119.             if (theErr == noErr) {
  3120.                 offSet = GetSndDataOffset(waveSnd4, &sndType, &waveLgth);
  3121.                 wavePtr = (Ptr)((long)*waveSnd1 + offSet);
  3122.                 theErr = InstallWave(chan4, wavePtr, waveLgth);
  3123.             }
  3124.         }
  3125.     }
  3126.     HUnlock((Handle)waveSnd1);                        // done with resources
  3127.     HPurge((Handle)waveSnd1);
  3128.     HUnlock((Handle)waveSnd2);
  3129.     HPurge((Handle)waveSnd2);
  3130.     HUnlock((Handle)waveSnd3);
  3131.     HPurge((Handle)waveSnd3);
  3132.     HUnlock((Handle)waveSnd4);
  3133.     HPurge((Handle)waveSnd4);
  3134.     return (theErr);                                // return the error
  3135. }
  3136.  
  3137. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3138. /*
  3139. This is the demonstration of the wave table synthesizers.  This will get
  3140. four snd resources that contain parts to a song.  Then I get the four wave
  3141. table channels.  With these four channels, I install two other snd
  3142. resources that contain wave table data.  Once the four songs, four
  3143. channels, and two wave tables are ready then I play the song.
  3144.  
  3145. BUG NOTE: The wave table synthesizer is not working on a non-Apple Sound
  3146. chip based Mac.  At least not so far with any System 6.0x release.  This
  3147. leaves the Mac Plus/SE without four tone polyphonic sound.
  3148.  
  3149. VERSION 1.2: No longer need to call HasWorkingWaveTables since Sound Manager
  3150. 2 and later fixed the problem.
  3151. */
  3152.  
  3153. #pragma segment Main
  3154. void PlayWaveMelody(void)
  3155. {
  3156.     SndListHandle    sndSong1, sndSong2, sndSong3, sndSong4;
  3157.     SndChannelPtr    chan1, chan2, chan3, chan4;
  3158.     OSErr            theErr;
  3159.  
  3160.     theErr = GetSndSongs(rMelodyPart1, rMelodyPart2, rMelodyPart3, rMelodyPart4,
  3161.                                 &sndSong1, &sndSong2, &sndSong3, &sndSong4);
  3162.     if (theErr != noErr) {
  3163.         AlertUser(theErr, sResErr);                // return the error
  3164.         return;                                    // we’re out of here
  3165.     }
  3166.     theErr = GetWaveChans(&chan1, &chan2, &chan3, &chan4);
  3167.     if (theErr == noErr) {
  3168.         theErr = InstallWaveSnds(chan1, chan2, chan3, chan4,
  3169.                             rWaveMelody, rWaveHarmony, rWaveHarmony, rWaveHarmony);
  3170.         if (theErr == noErr)
  3171.             theErr = Play4ChanSongs(chan1, chan2, chan3, chan4,
  3172.                                         sndSong1, sndSong2, sndSong3, sndSong4);
  3173.     }
  3174.     if (theErr == noErr)
  3175.         ShowStatusWindow(sMelodyMsg);
  3176.     else {                                        // catch any errors
  3177.         KillSound();
  3178.         AlertUser(theErr, sSoundErr);
  3179.     }
  3180. }
  3181.  
  3182. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3183. /*
  3184. This is the demonstration of the wave table synthesizers.  This will get
  3185. four snd resources that contain parts to a song.  Then I get the four wave
  3186. table channels.  With these four channels, I install four other snd resources
  3187. that contain wave table data.  Once the four songs, four channels, and
  3188. four wave tables are ready then I play the song.  By the way, SATB stands
  3189. for Soprano, Alto, Tenor, and Bass.  It’s standard music-speak.
  3190.  
  3191. BUG NOTE: The wave table synthesizer is not working on a non-Apple Sound
  3192. chip based Mac.  At least not so far with any System 6.0x release.  This
  3193. leaves the Mac Plus/SE without four tone polyphonic sound.
  3194.  
  3195. VERSION 1.2: No longer need to call HasWorkingWaveTables since Sound Manager
  3196. 2 and later fixed the problem.
  3197. */
  3198.  
  3199. #pragma segment Main
  3200. void PlayWaveSATB(void)
  3201. {
  3202.     SndListHandle    sndSong1, sndSong2, sndSong3, sndSong4;
  3203.     SndChannelPtr    chan1, chan2, chan3, chan4;
  3204.     OSErr            theErr;
  3205.  
  3206.     theErr = GetSndSongs(rCounterPt1, rCounterPt2, rCounterPt3, rCounterPt4,
  3207.                                 &sndSong1, &sndSong2, &sndSong3, &sndSong4);
  3208.     if (theErr != noErr) {
  3209.         AlertUser(theErr, sResErr);                    // return the error
  3210.         return;                                        // we’re out of here
  3211.     }
  3212.     theErr = GetWaveChans(&chan1, &chan2, &chan3, &chan4);
  3213.     if (theErr == noErr) {
  3214.         theErr = InstallWaveSnds(chan1, chan2, chan3, chan4,
  3215.                                     rSopranoVox, rAltoVox, rTenorVox, rBassVox);
  3216.         if (theErr == noErr)
  3217.             theErr = Play4ChanSongs(chan1, chan2, chan3, chan4,
  3218.                                         sndSong1, sndSong2, sndSong3, sndSong4);
  3219.     }
  3220.     if (theErr == noErr)
  3221.         ShowStatusWindow(sCounterPtMsg);
  3222.     else {                                            // catch any errors
  3223.         KillSound();
  3224.         AlertUser(theErr, sSoundErr);
  3225.     }
  3226. }
  3227.  
  3228. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3229. /*
  3230. VERSION 1.2: Create four sample sound channels with an instrument sound
  3231. installed in each one. Then play the four part song to demonstrate the
  3232. sample sound channel.
  3233. */
  3234.  
  3235. #pragma segment Main
  3236. void PlaySampleSATB(void)
  3237. {
  3238.     SndListHandle    sndSong1, sndSong2, sndSong3, sndSong4;
  3239.     SndListHandle    sampleHarmony;
  3240.     SndChannelPtr    chan1, chan2, chan3, chan4;
  3241.     OSErr            theErr;
  3242.  
  3243.     theErr = GetSndSongs(rCounterPt1, rCounterPt2, rCounterPt3, rCounterPt4,
  3244.                                 &sndSong1, &sndSong2, &sndSong3, &sndSong4);
  3245.     if (theErr != noErr) {
  3246.         AlertUser(theErr, sResErr);                    // return the error
  3247.         return;                                        // we’re out of here
  3248.     }
  3249.  
  3250.     sampleHarmony = (SndListHandle)Get1Resource(soundListRsrc, rSampleHarmony);
  3251.     theErr = Get4SampleInstruments(&chan1, &chan2, &chan3, &chan4,
  3252.                             sampleHarmony, sampleHarmony, sampleHarmony, sampleHarmony);
  3253.     if (theErr == noErr)
  3254.         theErr = Play4ChanSongs(chan1, chan2, chan3, chan4,
  3255.                                 sndSong1, sndSong2, sndSong3, sndSong4);
  3256.     if (theErr == noErr)
  3257.         ShowStatusWindow(sCounterPtMsg);
  3258.     else                                            // catch any errors
  3259.     {
  3260.         KillSound();
  3261.         AlertUser(theErr, sSoundErr);
  3262.     }
  3263. }
  3264.  
  3265. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3266. /*
  3267. VERSION 1.2: Create four sample sound channels with an instrument sound
  3268. installed in each one. Then play the four part song to demonstrate the
  3269. sample sound channel.
  3270. */
  3271.  
  3272. #pragma segment Main
  3273. void PlaySampleMelody(void)
  3274. {
  3275.     SndListHandle    sndSong1, sndSong2, sndSong3, sndSong4;
  3276.     SndListHandle    sampleHarmony, sampleMelody;
  3277.     SndChannelPtr    chan1, chan2, chan3, chan4;
  3278.     OSErr            theErr;
  3279.  
  3280.     theErr = GetSndSongs(rMelodyPart1, rMelodyPart2, rMelodyPart3, rMelodyPart4,
  3281.                                 &sndSong1, &sndSong2, &sndSong3, &sndSong4);
  3282.     if (theErr != noErr) {
  3283.         AlertUser(theErr, sResErr);                    // return the error
  3284.         return;                                        // we’re out of here
  3285.     }
  3286.  
  3287.     sampleHarmony = (SndListHandle)Get1Resource(soundListRsrc, rSampleHarmony);
  3288.     sampleMelody = (SndListHandle)Get1Resource(soundListRsrc, rSampleMelody);
  3289.     theErr = Get4SampleInstruments(&chan1, &chan2, &chan3, &chan4,
  3290.                             sampleMelody, sampleHarmony, sampleHarmony, sampleHarmony);
  3291.     if (theErr == noErr)
  3292.         theErr = Play4ChanSongs(chan1, chan2, chan3, chan4,
  3293.                                 sndSong1, sndSong2, sndSong3, sndSong4);
  3294.     if (theErr == noErr)
  3295.         ShowStatusWindow(sMelodyMsg);
  3296.     else                                            // catch any errors
  3297.     {
  3298.         KillSound();
  3299.         AlertUser(theErr, sSoundErr);
  3300.     }
  3301. }
  3302.  
  3303. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3304. /*
  3305. VERSION 1.1:  This is just one of the reasons I hate the Dialog Manager.
  3306. I needed a simple dialog to ask the user for a name for their new sound.
  3307. To do this, I only needed a simple dialog with two buttons and an
  3308. editable text item.  Since the ModalDialog will not draw an outline
  3309. around the default item, I then needed an userItem.  This is the really
  3310. stupid part. The userItem is only there just to get a chance to draw an
  3311. outline around the default button.  It has no other purpose.  It is not
  3312. visible, not does it get any user interaction what so ever.  It's just a
  3313. pain in the ass.
  3314. */
  3315.  
  3316. #pragma segment Main
  3317. pascal void DefaultOutline(WindowPtr window, short theItem)
  3318. {
  3319. #pragma unused (theItem)
  3320.     Handle itemHndl;
  3321.     Rect itemRect;
  3322.     short kind;
  3323.  
  3324.     GetDialogItem((DialogPtr)window, ok, &kind, &itemHndl, &itemRect);
  3325.     DoButtonOutline((ControlHandle)itemHndl);
  3326. }
  3327.  
  3328. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3329. /*
  3330. VERSION 1.1:  Show a dialog asking the user to name their new sound
  3331. resource.  I need to outline the default button, so I have to install an
  3332. userItem setting its drawing procedure to do the outline around a
  3333. different item altogether.  The Dialog Manager really bugs me.
  3334. */
  3335.  
  3336. #pragma segment Main
  3337. void GetSndName(Str255 sndName)
  3338. {
  3339.     DialogPtr dialog;
  3340.     Handle itemHndl;
  3341.     Rect itemRect;
  3342.     short kind;
  3343.     short theItem;
  3344.  
  3345.     dialog = GetNewDialog(rGetNameDLOG, nil, (WindowPtr)-1);
  3346.     GetDialogItem(dialog, rUserItem, &kind, &itemHndl, &itemRect);
  3347.     SetDialogItem(dialog, rUserItem, kind, (Handle)DefaultOutline, &itemRect);
  3348.     do
  3349.         ModalDialog(nil, &theItem);
  3350.     while ((theItem != ok) && (theItem != cancel));
  3351.     if (theItem == ok) {
  3352.         GetDialogItem(dialog, rNameItem, &kind, &itemHndl, &itemRect);
  3353.         GetDialogItemText(itemHndl, sndName);
  3354.     } else
  3355.         sndName[0] = 0;
  3356.     DisposeDialog(dialog);
  3357. }
  3358.  
  3359. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3360. /*
  3361. VERSION 1.1:  This routine adds the given snd resource to the file and
  3362. document. First thing to do is find a proper resource ID for the 'snd '.
  3363. There is a reserved range for them, didn't you read the documentation?
  3364. Once this new resource is added then I update the file and re-build the
  3365. list of sounds.  This is necessary since the list must be in the same
  3366. order as the sounds are in the file.  I ignore the error returned by
  3367. InitSndList, since the chances of it failing at this point are slim.  If
  3368. anything is wrong with the list, then the rest of this application is
  3369. robust enough to handle a resource problem.  The user would have to close
  3370. the document and attempt to open it again.  If adding the resources
  3371. works, but updating the file fails then I will remove it.  This keeps the
  3372. document consistent with the file.
  3373. */
  3374.  
  3375. #pragma segment Main
  3376. OSErr AddSnd(SndDocPeek sndDoc, StringPtr sndNamePtr, SndListHandle sndHndl)
  3377. {
  3378.     short resID;
  3379.     OSErr theErr;
  3380.     short ignore;
  3381.  
  3382.     UseResFile(sndDoc->resFile);                //put our resource in the right file
  3383.     do
  3384.         resID = Unique1ID(soundListRsrc);
  3385.     while (resID < kSystemSndRange);
  3386.     AddResource((Handle)sndHndl, soundListRsrc, resID, sndNamePtr);
  3387.     theErr = ResError();
  3388.     UseResFile(gAppResRef);                        //restore our resource file
  3389.     if (theErr == noErr) {
  3390.         UpdateResFile(sndDoc->resFile);            //update the file
  3391.         theErr = ResError();
  3392.         if (theErr == noErr) {
  3393.             ignore = FlushVol(nil, sndDoc->vRefNum);
  3394.             LDelRow(0, 0, sndDoc->list);        //delete all the rows
  3395.             ignore = InitSndList(sndDoc);        //re-create the list
  3396.             SelectSndCell(sndDoc, resID);        //select the new snd
  3397.         } else
  3398.             RemoveResource((Handle)sndHndl);    //couldn't add it, update failed
  3399.     }
  3400.     return(theErr);
  3401. }
  3402.  
  3403. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3404. /*
  3405. VERSION 1.1:  This routine has one tricky aspect involving the Resource
  3406. Manager and removing a resource.  There's a catch.  I want the document
  3407. to always reflect the contents of the file on disk.  In other words,
  3408. InitSndList depends on UpdateResFile returning noErr.  If the file is
  3409. locked, then removing a resource shouldn't be allowed but RmveResource
  3410. will return noErr even if the file cannot be updated.  This is a
  3411. "feature" since the user may unlock the volume after removing the
  3412. resource and then UpdateResFile would work.  If RmveResource succeeds,
  3413. but UpdateResFile fails then the resource map in memory will be
  3414. inconsistent with what's on disk.  If the user then closed the document
  3415. and opened it again, the resource they just removed would magically still
  3416. be there.  The basic problem is that it is difficult to determine if a
  3417. given file will really allow write access.  There's at least three
  3418. situations to check: a locked file, a locked volume, or an AppleShare
  3419. folder privileges issue.  The ideal, and probably the best, solution
  3420. would be to deselect the edit commands from the user for a read-only
  3421. file.  This would involve lots of File Manager calls every time the user
  3422. selects a menu command.  (If you thought that GetFCBInfo would tell you
  3423. this, you're wrong.  You can have write permission to a file that is on a
  3424. locked volume.)  Additionally, the user needs to see that the reason the
  3425. edit menu doesn't work is because the file is read-only which would
  3426. require another feature to be added with lots more code.  This is why I
  3427. call ChangedResource before any other Resource Manager calls.
  3428. ChangedResource will determine if the resource can be written to disk.
  3429. If not, then it returns an error which is exactly what I wanted to know
  3430. in the first place.  I want to flush the cache to keep the disk's
  3431. resource map consistent with the resource data.  Otherwise, a crash could
  3432. occur the resource fork might be damaged and the file has to be repaired
  3433. (if possible) or deleted.  I'm ignoring the InitSndList result.  At this
  3434. stage, there's only a slim chance the list couldn't be re-built.  If it
  3435. does fail, the file should be closed.
  3436.  
  3437. A tip to the reader: dispose of as much memory as possible before calling
  3438. UpdateResFile.  This makes it faster.  UpdateResFile will not purge any
  3439. memory, but only attempts to use the available space.  If there's little
  3440. free space then UpdateResFile will run really slow.
  3441. */
  3442.  
  3443. #pragma segment Main
  3444. void ClearSnd(SndDocPeek sndDoc)
  3445. {
  3446.     SndListHandle    sndHndl;
  3447.     OSErr            theErr;
  3448.     short            ignore;
  3449.  
  3450.     theErr = GetSelection(sndDoc, &sndHndl);            //get the resource to remove
  3451.     if (theErr == noErr) {
  3452.         ChangedResource((Handle)sndHndl);                //can we change the file?
  3453.         theErr = ResError();                            //save the error result
  3454.         if (theErr == noErr) {
  3455.             UseResFile(sndDoc->resFile);                //use the right resource file
  3456.             RemoveResource((Handle)sndHndl);            //remove that sucker
  3457.             theErr = ResError();                        //save the error result
  3458.             UseResFile(gAppResRef);                        //restore our resource file
  3459.             if (theErr == noErr) {
  3460.                 DisposeHandle((Handle)sndHndl);            //get rid of the memory
  3461.                 UpdateResFile(sndDoc->resFile);            //update the file
  3462.                 theErr = ResError();                    //save the error result
  3463.                 if (theErr == noErr)
  3464.                     ignore = FlushVol(nil, sndDoc->vRefNum);
  3465.                 LDelRow(0, 0, sndDoc->list);            //delete all the rows
  3466.                 ignore = InitSndList(sndDoc);            //re-create the list
  3467.                 SelectNextCell(sndDoc->list, true);     //select the first cell
  3468.                 ActivateSndCntls(sndDoc);                //may not be any sounds left
  3469.             }
  3470.         }
  3471.     }
  3472.     if (theErr != noErr)
  3473.         AlertUser(theErr, sEditErr);
  3474. }
  3475.  
  3476. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3477. /*
  3478. VERSION 1.1:  This routine will create a handle and record sound into it.
  3479. A new sound will prompt the user for a name to add it to the document.
  3480. The Sound Input Manager will re-size this handle to be as small as
  3481. possible to contain only the samples recorded.  You can pass sndHandl ==
  3482. nil to SndRecord, which will cause the Sound Input Manager to create a
  3483. handle for you.  If adding the new sound is successful, the new resource
  3484. handle is marked purgeable, because I only use them temporally and they
  3485. tend to be large.  I have to set the sndHandle variable to nil in this
  3486. case since it is now belongs to the Resource Manager and I don't want to
  3487. dispose of it in the error handling code.  The choice of recording
  3488. quality wasn't given to the user.  Typically, users would only be
  3489. confused by the question of "what compression ratio do you prefer?"  As
  3490. a power user option, it would be nice to let the user set the rate.  Be
  3491. careful since this is a user interface issue, and Apple expects to see
  3492. lots of Sound Input features in applications.
  3493. */
  3494.  
  3495. #pragma segment Main
  3496. void DoRecordSound(SndDocPeek sndDoc)
  3497. {
  3498.     Str255            sndName;
  3499.     Point            recTopLeft;
  3500.     long            total;
  3501.     long            contig;
  3502.     SndListHandle    sndHandle;
  3503.     OSErr            theErr;
  3504.  
  3505.     KillSound();
  3506.     PurgeSpace(&total, &contig);
  3507.     sndHandle = (SndListHandle)NewHandle(contig - kMinSpace);
  3508.     if (sndHandle != nil) {
  3509.         recTopLeft.v = kRecordTop;
  3510.         recTopLeft.h = kRecordLeft;
  3511.         theErr = SndRecord(nil, recTopLeft, siBestQuality, &sndHandle);
  3512.         if (theErr == noErr) {
  3513.             GetSndName(sndName);
  3514.             theErr = AddSnd(sndDoc, sndName, sndHandle);
  3515.             if (theErr == noErr) {
  3516.                 HPurge((Handle)sndHandle);
  3517.                 sndHandle = nil;
  3518.             }
  3519.         }
  3520.     } else
  3521.         theErr = MemError();
  3522.     if (sndHandle != nil)
  3523.         DisposeHandle((Handle)sndHandle);
  3524.     if ((theErr != noErr) && (theErr != userCanceledErr))
  3525.         AlertUser(theErr, sSoundErr);
  3526. }
  3527.  
  3528. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3529. /*
  3530. Enable and disable menus based on the current state.  The user can only
  3531. select enabled menu items so I set up all the menu items before calling
  3532. MenuSelect or MenuKey, since these are the only times that a menu item
  3533. can be selected. Note that MenuSelect is also the only time the user will
  3534. see menu items. This approach to deciding what enable/disable state a menu
  3535. item has the advantage of concentrating all the decision making in one
  3536. routine, as opposed to being spread throughout the application.  Other
  3537. application designs may take a different approach that may or may not be
  3538. just as valid.
  3539. */
  3540.  
  3541. #pragma segment Main
  3542. void AdjustMenus(void)
  3543. {
  3544.      MenuHandle menu;
  3545.     WindowPtr window;
  3546.     Boolean allowEdit;
  3547.  
  3548.     window = FrontWindow();
  3549.     menu = GetMenuHandle(mFile);                    //the File menu and items
  3550.     if (IsDAWindow(window) || IsDocWindow(window))
  3551.         EnableItem(menu, iClose);
  3552.     else
  3553.         DisableItem(menu, iClose);
  3554.  
  3555.     menu = GetMenuHandle(mEdit);                    //the Edit menu and items
  3556.     allowEdit = IsDAWindow(window);
  3557.     if (allowEdit)                                    //check the undo item
  3558.         EnableItem(menu, iUndo);
  3559.     else
  3560.         DisableItem(menu, iUndo);
  3561.  
  3562.     if (IsDocWindow(window)) {                        //handle the other edit items
  3563.         allowEdit = HasSelection((SndDocPeek)window) || allowEdit;
  3564.         EnableItem(menu, iPaste);
  3565.     } else
  3566.         DisableItem(menu, iPaste);
  3567.  
  3568.     if (allowEdit) {
  3569.         EnableItem(menu, iCut);
  3570.         EnableItem(menu, iCopy);
  3571.         EnableItem(menu, iClear);
  3572.     } else {
  3573.         DisableItem(menu, iCut);
  3574.         DisableItem(menu, iCopy);
  3575.         DisableItem(menu, iClear);
  3576.     }
  3577. }
  3578.  
  3579. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3580. /*
  3581. VERSION 1.1:  Get the currently selected item and copy it to the
  3582. clipboard.  I want to also save the name for this resource, so I add a
  3583. string type to the clipboard as well.
  3584. */
  3585.  
  3586. #pragma segment Main
  3587. void CopySnd(SndDocPeek sndDoc)
  3588. {
  3589.     Str255            sndName;
  3590.     ResType            rType;
  3591.     SndListHandle    sndHndl;
  3592.     long            scrapLen;
  3593.     short            id;
  3594.     OSErr            theErr;
  3595.  
  3596.     theErr = GetSelection(sndDoc, &sndHndl);
  3597.     if (theErr == noErr) {
  3598.         GetResInfo((Handle)sndHndl, &id, &rType, sndName);
  3599.         scrapLen = ZeroScrap();                        //ignoring the result
  3600.         theErr = PutScrap(StrLength(sndName) + 1, 'STR ', sndName);
  3601.         HLock((Handle)sndHndl);
  3602.         theErr = PutScrap(GetHandleSize((Handle)sndHndl), soundListRsrc, (Ptr)(*sndHndl));
  3603.         HUnlock((Handle)sndHndl);
  3604.         HPurge((Handle)sndHndl);
  3605.     }
  3606.     if (theErr != noErr)
  3607.         AlertUser(theErr, sEditErr);
  3608. }
  3609.  
  3610. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3611. /*
  3612. VERSION 1.1:  Copy the selection and then delete it.
  3613. */
  3614.  
  3615. #pragma segment Main
  3616. void CutSnd(SndDocPeek sndDoc)
  3617. {
  3618.     CopySnd(sndDoc);
  3619.     ClearSnd(sndDoc);
  3620. }
  3621.  
  3622. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3623. /*
  3624. VERSION 1.1:  This routine will create a new resource into the file
  3625. containing the clipboard's sound data.  A name is attempted to be found
  3626. by first checking for the string type in the scrap.  This application
  3627. will always put both a string and a sound together on the clipboard.  But
  3628. if the user copied a sound from the Sound cdev, ResEdit, or by some other
  3629. method then I'll ask the user for a new name.  If adding the new resource
  3630. is successful, then I mark the resource as purgeable and set the sndHndl
  3631. variable to NIL.  The Resource Manager then owns the handle and I don't
  3632. want my error handling to dispose of this new handle.
  3633. */
  3634.  
  3635. #pragma segment Main
  3636. void PasteSnd(SndDocPeek sndDoc)
  3637. {
  3638.     Str255            sndName;
  3639.     StringHandle    sndNameHndl;
  3640.     long            offset;
  3641.     long            scrapLen;
  3642.     SndListHandle    sndHndl;
  3643.     OSErr            theErr;
  3644.  
  3645.     sndHndl = (SndListHandle)NewHandle(0);
  3646.     sndNameHndl = NewString("\p");
  3647.     theErr = MemError();
  3648.     scrapLen = GetScrap((Handle)sndNameHndl, 'STR ', &offset);
  3649.     scrapLen = GetScrap((Handle)sndHndl, soundListRsrc, &offset);
  3650.     if (scrapLen > 0) {
  3651.         if (sndNameHndl != nil)
  3652.             PStringCopy(*sndNameHndl, sndName);
  3653.         else
  3654.             sndName[0] = 0;
  3655.         if (StrLength(sndName) == 0)
  3656.             GetSndName(sndName);
  3657.         theErr = AddSnd(sndDoc, sndName, sndHndl);
  3658.         if (theErr == noErr) {
  3659.             HPurge((Handle)sndHndl);
  3660.             sndHndl = nil;                                        //done with handle
  3661.             ActivateSndCntls(sndDoc);
  3662.         }
  3663.     } else
  3664.         theErr = scrapLen;
  3665.  
  3666.     if (sndHndl != nil)
  3667.         DisposeHandle((Handle)sndHndl);
  3668.     if (sndNameHndl != nil)
  3669.         DisposeHandle((Handle)sndNameHndl);
  3670.     if (theErr != noErr)
  3671.         AlertUser(theErr, sEditErr);
  3672. }
  3673.  
  3674. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3675. /*
  3676. This is called when an item is chosen from the menu bar (after calling
  3677. MenuSelect or MenuKey). It performs the right operation for each command.
  3678. It is good to have both the result of MenuSelect and MenuKey go to
  3679. one routine like this to keep everything organized.
  3680.  
  3681. VERSION 1.1:  Supporting the edit commands for snd resources.
  3682. */
  3683.  
  3684. #pragma segment Main
  3685. void DoMenuCommand(long menuResult)
  3686. {
  3687.     WindowPtr window;
  3688.     short menuID;
  3689.     short menuItem;                            //resource ID and item of the selected menu
  3690.     short daRefNum;
  3691.     Str255 daName;
  3692.     Boolean ignore;
  3693.  
  3694.     menuID = HighWord(menuResult);            //use macros for efficiency...
  3695.     menuItem = LowWord(menuResult);            //to get menu item number and menu number
  3696.     switch (menuID) {
  3697.  
  3698.         case mApple:
  3699.             switch (menuItem) {
  3700.                 case iAbout:                //bring up alert for About
  3701.                     DoAbout();
  3702.                     break;
  3703.                 default:                    //all non-About items in this menu are DAs
  3704.                     GetMenuItemText(GetMenuHandle(mApple), menuItem, daName);
  3705.                     daRefNum = OpenDeskAcc(daName);
  3706.                     break;
  3707.             }
  3708.             break;
  3709.  
  3710.         case mFile:
  3711.             switch (menuItem) {
  3712.                 case iNew:
  3713.                     NewSoundDoc();
  3714.                     break;
  3715.                 case iOpen:
  3716.                     GetSoundDoc();
  3717.                     break;
  3718.                 case iClose:
  3719.                     ignore = DoCloseWindow(FrontWindow()); //I don’t care if cancelled
  3720.                     break;
  3721.                 case iQuit:
  3722.                     Terminate();
  3723.                     break;
  3724.             }
  3725.             break;
  3726.  
  3727.         case mEdit:                                //call SystemEdit for DA editing && MultiFinder
  3728.             if (! SystemEdit(menuItem - 1)) {    //since I don’t do any editing
  3729.                 window = FrontWindow();
  3730.                 if (IsDocWindow(window)) {
  3731.                     switch (menuItem) {
  3732.  
  3733.                         case iCut:
  3734.                             CutSnd((SndDocPeek)window);
  3735.                             break;
  3736.                         case iCopy:
  3737.                             CopySnd((SndDocPeek)window);
  3738.                             break;
  3739.                         case iPaste:
  3740.                             PasteSnd((SndDocPeek)window);
  3741.                             break;
  3742.                         case iClear:
  3743.                             ClearSnd((SndDocPeek)window);
  3744.                             break;
  3745.                     }
  3746.                 }
  3747.             }
  3748.             break;
  3749.  
  3750.         case mDemos:
  3751.             switch (menuItem) {
  3752.  
  3753.                 case iCheckVolume:
  3754.                     CheckSoundVolume();
  3755.                     break;
  3756.  
  3757.                 case iSquareScale:
  3758.                     PlaySquareSong(rScaleSnd);
  3759.                     break;
  3760.  
  3761.                 case iSquareMelody:
  3762.                     PlaySquareSong(rMelodyPart1);
  3763.                     break;
  3764.  
  3765.                 case iSquareTimbre:
  3766.                     PlaySquareTimbres();
  3767.                     break;
  3768.  
  3769.                 case iWaveScale:
  3770.                     PlayWaveScale();
  3771.                     break;
  3772.  
  3773.                 case iWaveMelody:
  3774.                     PlayWaveMelody();
  3775.                     break;
  3776.  
  3777.                 case iWaveSATB:
  3778.                     PlayWaveSATB();
  3779.                     break;
  3780.  
  3781.                 case iSampleMelody:
  3782.                     PlaySampleMelody();
  3783.                     break;
  3784.  
  3785.                 case iSampleSATB:
  3786.                     PlaySampleSATB();
  3787.                     break;
  3788.  
  3789.             } //switch (menuItem)
  3790.  
  3791.     } //switch (menuID)
  3792.     HiliteMenu(0);                        //unhighlight what MenuSelect or MenuKey hilited
  3793. }
  3794.  
  3795. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3796. /*
  3797. Draw the contents of the application window in response to an update
  3798. event.  At this point, BeginUpdate has been called which sets the window’s
  3799. visRgn to clip drawing only where it needs to be done.  I have the
  3800. controls to draw, a list to update, and a default button to outline.  I
  3801. use UpdateControls to avoid needless drawing that happens with DrawControls.
  3802. It not only runs faster but doesn’t flicker.
  3803. */
  3804.  
  3805. #pragma segment Main
  3806. void DrawSndWindow(WindowPtr window)
  3807. {
  3808.     ControlHandle control;
  3809.     Rect theRect;
  3810.  
  3811.     PenNormal();
  3812.     LUpdate(window->visRgn, ((SndDocPeek)window)->list);    // update list
  3813.     theRect = (**((SndDocPeek)window)->list).rView;            // frame the list
  3814.     theRect.right = theRect.right + kScrollbarAdjust;
  3815.     InsetRect(&theRect, kListFrameInset, kListFrameInset);
  3816.     FrameRect(&theRect);
  3817.     UpdateControls(window, window->visRgn);                    // update controls
  3818.     control = (ControlHandle)((WindowPeek)window)->controlList;            // draw button outline
  3819.     while (control != nil) {
  3820.         if (GetControlReference(control) == rPlaySndCntl)
  3821.             DoButtonOutline(control);
  3822.         control = (**control).nextControl;
  3823.     }
  3824. }
  3825.  
  3826. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3827. /*
  3828. When the user types a key, I check if it is one that I’m looking for.
  3829. This routine only handles the non-command key events.  Here I’m looking
  3830. for a arrow key or the return and enter keys for the default button.
  3831.  
  3832. VERSION 1.1: The enter and return keys only work if there is a selection.
  3833. Now supporting the backspace and delete keys which clear the selection.
  3834. */
  3835.  
  3836. #pragma segment Main
  3837. void DoKeyDown(char key, WindowPtr window)
  3838. {
  3839.     ControlHandle control;
  3840.     Boolean ignore;
  3841.  
  3842.     switch (GetWRefCon(window)) {
  3843.  
  3844.         case rSoundWindow:
  3845.             switch (key) {
  3846.  
  3847.                 case kEnterKey:
  3848.                 case kReturnKey:
  3849.                     if (HasSelection((SndDocPeek)window)) {
  3850.                         control = (ControlHandle)((WindowPeek)window)->controlList;
  3851.                         while (control != nil) {            //find the default button
  3852.                             if (GetControlReference(control) == rPlaySndCntl)
  3853.                                 SelectButton(control);            //here it is
  3854.                             control = (**control).nextControl;
  3855.                         }
  3856.                         PlaySelectedSnd((SndDocPeek)window, sPlayingMsg);
  3857.                     }
  3858.                     break;
  3859.  
  3860.                 case kUpArrow:
  3861.                     SelectNextCell(((SndDocPeek)window)->list, false);
  3862.                     ActivateSndCntls((SndDocPeek)window);
  3863.                     break;
  3864.  
  3865.                 case kDownArrow:
  3866.                     SelectNextCell(((SndDocPeek)window)->list, true);
  3867.                     ActivateSndCntls((SndDocPeek)window);
  3868.                     break;
  3869.  
  3870.                 case kBackspace:
  3871.                     ClearSnd((SndDocPeek)window);
  3872.                     break;
  3873.             }
  3874.             break; //rSoundWindow
  3875.  
  3876.         case rStatusWindow:
  3877.             if (    (key == kEnterKey)
  3878.                  || (key == kReturnKey)
  3879.                  || (key == kEscape) ) {
  3880.                 SelectButton((ControlHandle)((WindowPeek)window)->controlList);
  3881.                 KillSound();
  3882.             }
  3883.             break;
  3884.  
  3885.         case rAboutWindow:
  3886.             if (    (key == kEnterKey)
  3887.                  || (key == kReturnKey)
  3888.                  || (key == kEscape) ) {
  3889.                 SelectButton((ControlHandle)((WindowPeek)window)->controlList);
  3890.                 ignore = DoCloseWindow(window);
  3891.             }
  3892.             break;
  3893.     } //switch (GetWRefCon(window))
  3894. }
  3895.  
  3896. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3897. /*
  3898. Given a document, this will handle any clicking in the list.  The mouse
  3899. point (event.where) is expected to have been adjusted to the local
  3900. coordinates of the window.  If this routine does handle the event, then
  3901. I return true.
  3902.  
  3903. BUG NOTE: LClick will return a double-click even if no cell was selected.
  3904. So I have to test for the last click being in a real cell.  If not, then
  3905. I will not process the double click.  Also, there is another bug in the
  3906. List Manager.  It will not always deselect the currently selected cell when
  3907. the user clicks outside of the data bounds.  In other words, sometimes
  3908. my list would show 4 items when the list has room to show 8.  If the user
  3909. clicked in the bottom area of the list (below the last item) the List
  3910. Manager should deselect any items.  It doesn’t all the time, just sometimes.
  3911. The only real solution would be to write a new LClick.
  3912. */
  3913.  
  3914. #pragma segment Main
  3915. Boolean ListClick(SndDocPeek sndDoc, EventRecord *event)
  3916. {
  3917.     Cell aCell;
  3918.     Rect listRect;
  3919.     Boolean result;
  3920.  
  3921.     listRect = (**(sndDoc->list)).rView;
  3922.     listRect.right = listRect.right + kScrollbarAdjust;
  3923.     if (PtInRect(event->where, &listRect)) {
  3924.         if (LClick(event->where, event->modifiers, sndDoc->list)) {
  3925.             aCell = LLastClick(sndDoc->list);
  3926.             if ( PtInRect(aCell, &((**(sndDoc->list)).dataBounds)) )
  3927.                 PlaySelectedSnd(sndDoc, sPlayingMsg);
  3928.         }
  3929.         ActivateSndCntls(sndDoc);
  3930.         result = true;                                    //I handled the event
  3931.     } else
  3932.         result = false;
  3933.     return(result);
  3934. }
  3935.  
  3936. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3937. /*
  3938. This is called when a mouse-down event occurs in the content of my
  3939. application windows.  First thing to check for is a click in the list.
  3940. If not a list click, then find what control may have been clicked in and
  3941. handle that.
  3942.  
  3943. VERSION 1.1: Handle the record button.
  3944. */
  3945.  
  3946. #pragma segment Main
  3947. void DoSndDocClick(SndDocPeek sndDoc, EventRecord *event)
  3948. {
  3949.     ControlHandle control;
  3950.  
  3951.     SetPort((GrafPtr)sndDoc);
  3952.     GlobalToLocal(&event->where);
  3953.     if (! ListClick(sndDoc, event)) {
  3954.         if (FindControl(event->where, (WindowPtr)sndDoc, &control) != 0) {
  3955.             if (TrackControl(control, event->where, nil) != 0) {
  3956.                 switch (GetControlReference(control)) {
  3957.  
  3958.                     case rPlaySndCntl:
  3959.                         PlaySelectedSnd(sndDoc, sPlayingMsg);
  3960.                         break;
  3961.  
  3962.                     case rHyperPlayCntl:
  3963.                         PlaySelectedSnd(sndDoc, sHyperMsg);
  3964.                         break;
  3965.  
  3966.                     case rPlayScaleCntl:
  3967.                         PlaySndSong(sndDoc, rScaleSnd);
  3968.                         break;
  3969.  
  3970.                     case rMelodyCntl:
  3971.                         PlaySndSong(sndDoc, rMelodyPart1);
  3972.                         break;
  3973.  
  3974.                     case rStopCntl:
  3975.                         KillSound();
  3976.                         break;
  3977.  
  3978.                     case rRecordCntl:
  3979.                         DoRecordSound(sndDoc);
  3980.                         break;
  3981.  
  3982.                 } //switch GetControlReference(control)
  3983.             } //if TrackControl
  3984.         } //if FindControl
  3985.     } //if ! ListSelect
  3986. }
  3987.  
  3988. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3989. /*
  3990. The status window has a stop button.  This will stop any sound in
  3991. progress.  So, if the user clicks in my status window I need to check
  3992. for this.
  3993. */
  3994.  
  3995. #pragma segment Main
  3996. void DoStatClick(StatWindowPeek statWindow, EventRecord *event)
  3997. {
  3998.     ControlHandle control;
  3999.  
  4000.     SetPort((GrafPtr)statWindow);
  4001.     GlobalToLocal(&(event->where));
  4002.     if (FindControl(event->where, (WindowPtr)statWindow, &control) != 0)
  4003.         if (TrackControl(control, event->where, nil) != 0)
  4004.             KillSound();
  4005. }
  4006.  
  4007. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4008. /*
  4009. The about window has a single OK button.  If the users clicks in it, then
  4010. close the window.
  4011. */
  4012.  
  4013. #pragma segment Main
  4014. void DoAboutClick(WindowPtr window, EventRecord *event)
  4015. {
  4016.     ControlHandle control;
  4017.     Boolean ignore;
  4018.  
  4019.     SetPort(window);
  4020.     GlobalToLocal(&event->where);
  4021.     if (FindControl(event->where, (WindowPtr)window, &control) != 0) {
  4022.         if (TrackControl(control, event->where, nil) != 0)
  4023.             ignore = DoCloseWindow(window);
  4024.     }
  4025. }
  4026.  
  4027. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4028. /*
  4029. This is called when an update event is received for any of my windows.  It
  4030. calls the appropriate window’s update routine to draw its contents.  As an
  4031. efficiency measure that does not have to be followed, it calls the drawing
  4032. routine only if the visRgn is non-empty.  This will handle situations
  4033. where calculations for drawing or drawing itself is very time-consuming.
  4034. Why does QD give you an update with an empty updateRgn?
  4035. */
  4036.  
  4037. #pragma segment Main
  4038. void DoUpdate(WindowPtr window)
  4039. {
  4040.     BeginUpdate(window);                            //setup the visRgn, clears updateRgn
  4041.     if (! EmptyRgn(window->visRgn)) {                 //if updating to be done
  4042.         SetPort(window);                            //set to the current port
  4043.         switch (GetWRefCon(window)) {                //call the window’s drawing routine
  4044.  
  4045.             case rSoundWindow:
  4046.                 DrawSndWindow(window);
  4047.                 break;
  4048.  
  4049.             case rStatusWindow:
  4050.                 DrawStatusWindow();
  4051.                 break;
  4052.  
  4053.             case rAboutWindow:
  4054.                 DrawAboutWindow(window);
  4055.                 break;
  4056.         }
  4057.     }
  4058.     EndUpdate(window);                                //restores the visRgn
  4059. }
  4060.  
  4061. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4062. /*
  4063. This is called when a window is to be activated or deactivated.  For the
  4064. document window I activate all the controls and the list.  For the status
  4065. window I activate the one and only control.  This is also called for
  4066. suspend and resume events while running MultiFinder.
  4067. */
  4068.  
  4069. #pragma segment Main
  4070. void DoActivate(WindowPtr window, Boolean becomingActive)
  4071. {
  4072.     if (window != nil) {
  4073.         switch (GetWRefCon(window)) {
  4074.  
  4075.             case rSoundWindow:
  4076.                 ActivateSndCntls((SndDocPeek)window);
  4077.                 LActivate(becomingActive, ((SndDocPeek)window)->list);
  4078.                 break;
  4079.  
  4080.             case rStatusWindow:
  4081.                 if (becomingActive)                            //it only has one control
  4082.                     HiliteControl((ControlHandle)((WindowPeek)window)->controlList, kControlNoPart);
  4083.                 else
  4084.                     HiliteControl((ControlHandle)((WindowPeek)window)->controlList, kControlInactivePart);
  4085.                 DoButtonOutline((ControlHandle)((WindowPeek)window)->controlList);
  4086.                 break;
  4087.  
  4088.             case rAboutWindow:
  4089.                 if (becomingActive)                            //it only has one control
  4090.                     HiliteControl((ControlHandle)((WindowPeek)window)->controlList, kControlNoPart);
  4091.                 else
  4092.                     HiliteControl((ControlHandle)((WindowPeek)window)->controlList, kControlInactivePart);
  4093.                 DoButtonOutline((ControlHandle)((WindowPeek)window)->controlList);
  4094.                 break;
  4095.         }
  4096.     }
  4097. }
  4098.  
  4099. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4100. /*
  4101. The required AppleEvent sent to tell an application to quit. Nothing much to do.
  4102. Just call our terminate routine to clean up and then exit through the event loop.
  4103. Note that you cannot exit from here, the system will crash. You must return to
  4104. the AppleEvent Manager. Do not call ExitToShell at this point!
  4105. */
  4106.  
  4107. #pragma segment Main
  4108. pascal OSErr QuitApplicationEvent(const AppleEvent *theAppleEvent, AppleEvent *reply, long handlerRefcon)
  4109. {
  4110. #pragma unused (theAppleEvent, reply, handlerRefcon)
  4111.  
  4112.     Terminate();
  4113.     return(noErr);
  4114. }
  4115.  
  4116. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4117. /*
  4118. One of the required AppleEvents. This is a request to open a document. Find
  4119. the document being requested, and open it.
  4120. */
  4121.  
  4122. #pragma segment Main
  4123. pascal OSErr OpenDocumentsEvent(const AppleEvent *theAppleEvent, AppleEvent *reply, long handlerRefcon)
  4124. {
  4125. #pragma unused (reply, handlerRefcon)
  4126.  
  4127.     FSSpec                file;
  4128.     AEDescList            docList;
  4129.     long                i;
  4130.     long                itemsInList;
  4131.     Size                actualSize;
  4132.     AEKeyword            keyword;
  4133.     DescType            returnedType;
  4134.     OSErr                theErr;
  4135.  
  4136.     // get the direct parameter--a descriptor list--and put it into docList
  4137.     theErr = AEGetParamDesc(theAppleEvent, keyDirectObject, typeAEList, &docList);
  4138.     if (theErr == noErr)
  4139.     {
  4140.         if (docList.descriptorType != typeAEList)
  4141.         {
  4142.             AEDisposeDesc (&docList);
  4143.             theErr = paramErr;
  4144.         }
  4145.         else
  4146.         {
  4147.             // count the number of descriptor records in the list
  4148.             theErr = AECountItems(&docList, &itemsInList);
  4149.             if (theErr == noErr)
  4150.             {
  4151.                 //get each descriptor record from the list, coerce the returned data
  4152.                 //to an FSSpec and open the associated file
  4153.  
  4154.                 for (i = 1; i <= itemsInList; i++)
  4155.                 {
  4156.                     theErr = AEGetNthPtr(&docList, i, typeFSS, &keyword, &returnedType,
  4157.                                             &file, sizeof(file), &actualSize);
  4158.                     if (theErr == noErr)
  4159.                         OpenSoundDoc(&file);
  4160.                 }
  4161.             }
  4162.             AEDisposeDesc (&docList);
  4163.         }
  4164.     }
  4165.     return (theErr);
  4166. }
  4167.  
  4168. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4169. /*
  4170. It's a required AppleEvent and we don't use it.
  4171. */
  4172.  
  4173. #pragma segment Main
  4174. pascal OSErr PrintDocumentsEvent(const AppleEvent *theAppleEvent, AppleEvent *reply, long handlerRefcon)
  4175. {
  4176. #pragma unused (theAppleEvent, reply, handlerRefcon)
  4177.  
  4178.     return (errAEEventNotHandled);
  4179. }
  4180.  
  4181. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4182. /*
  4183. It's a required AppleEvent and we don't use it.
  4184. */
  4185.  
  4186. #pragma segment Main
  4187. pascal OSErr OpenApplicationEvent(const AppleEvent *theAppleEvent, AppleEvent *reply, long handlerRefcon)
  4188. {
  4189. #pragma unused (theAppleEvent, reply, handlerRefcon)
  4190.  
  4191.     return (noErr);
  4192. }
  4193.  
  4194. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4195. /*
  4196. As Spike Lee says, “Do the right thing.” Determine what kind of event it
  4197. is, and call the appropriate routines.  Key down events are first tested
  4198. as being command key events for menus or command-. for cancel.  If it’s
  4199. the command-. the user is asking to cancel the sound.  In this case, if
  4200. the front window is the status window then the button should look as if it
  4201. has been clicked.  This is proper human interface.  Any non-menu command
  4202. keys are passed to DoKeyDown.  I have a global flag, gInModalState, which
  4203. is used to handle the front window as a modal dialog.  This means I ignore
  4204. clicks outside of the modal window and menu command keys.  I could have a
  4205. different global flag that would mean it’s a modal window but uses menu
  4206. commands, such as gInModalMenuState.  An important note is that I do pass
  4207. any other non-menu command keys to DoKeys, so the modal window could have
  4208. access to key events.  One last thing to note happens during a suspend
  4209. event.   Applications using sound should dispose of their sound channels
  4210. at suspend time.  No other application can use sound while another one has
  4211. channels allocated.  To stop my sound, I call KillSound which hides the
  4212. status window.  MultiFinder does properly deactivate the front window at
  4213. suspend time and applications normally do not have to worry about
  4214. HiliteWindow.  I do because the front window could have been the status
  4215. window and I’ve removed it after getting a suspend event.  This causes the
  4216. next window, a document window, to become highlighted as the active
  4217. window.  To avoid my next window from being highlighted while in the
  4218. background, I have to call HiliteWindow *after* KillSound.  This is
  4219. strange and only applications changing the front window at suspend event
  4220. time have to be concerned about this.
  4221.  
  4222. VERSION 1.1: Added a constant, kSFTopLeft, to specify the dialog position.
  4223. I do not call KillSound during a MultiFinder switch unless we're running
  4224. the older Sound Manager.  The new one allows for multiple sound
  4225. channels or will return the proper error otherwise.
  4226. */
  4227.  
  4228. #pragma segment Main
  4229. void DoEvent(EventRecord *event)
  4230. {
  4231.     WindowPtr window;
  4232.     Point where;
  4233.     short part;
  4234.     short err;
  4235.     Boolean ignore;
  4236.     char key;
  4237.  
  4238.     switch (event->what) {
  4239.  
  4240.         case mouseDown:
  4241.             part = FindWindow(event->where, &window);
  4242.             if (    (IsModalWindow(FrontWindow()) && (window != FrontWindow()))
  4243.                  || (IsModalWindow(FrontWindow()) && (part == inMenuBar)))
  4244.             {
  4245.                 SysBeep(30);                            //click outside of modal window
  4246.                 return;                                    //break out of routine
  4247.             }
  4248.             switch (part) {
  4249.                 case inMenuBar:                                //process the menu command
  4250.                     AdjustMenus();
  4251.                     DoMenuCommand(MenuSelect(event->where));
  4252.                     break;
  4253.  
  4254.                 case inSysWindow:                            //let system handle the mouseDown
  4255.                     SystemClick(event, window);
  4256.                     break;
  4257.  
  4258.                 case inContent:
  4259.                     if ((window != FrontWindow()))
  4260.                         SelectWindow(window);
  4261.                     else {
  4262.                         switch (GetWRefCon(window)) {
  4263.  
  4264.                             case rSoundWindow:
  4265.                                 DoSndDocClick((SndDocPeek)window, event);
  4266.                                 break;
  4267.  
  4268.                             case rStatusWindow:
  4269.                                 DoStatClick((StatWindowPeek)window, event);
  4270.                                 break;
  4271.  
  4272.                             case rAboutWindow:
  4273.                                 DoAboutClick(window, event);
  4274.                                 break;
  4275.  
  4276.                             } //switch (GetWRefCon(window))
  4277.                         }
  4278.                     break; //inContent
  4279.  
  4280.                 case inDrag:                        //pass screenBits.bounds to get all gDevices
  4281.                     DragWindow(window, event->where, &qd.screenBits.bounds);
  4282.                     break;
  4283.  
  4284.                 case inGoAway:
  4285.                     if (TrackGoAway(window, event->where))
  4286.                         ignore = DoCloseWindow(window);
  4287.                     break;
  4288.  
  4289.             } //switch (part)
  4290.             break; //mouseDown
  4291.  
  4292.         case keyDown:
  4293.         case autoKey:
  4294.             window = FrontWindow();
  4295.             key = event->message & charCodeMask;
  4296.             if ((event->modifiers & cmdKey) != 0)            //Command key down?
  4297.             {
  4298.                 if (key == kPeriod)
  4299.                 {
  4300.                     if (window == (WindowPtr)gStatusWindow)
  4301.                         SelectButton((ControlHandle)((WindowPeek)gStatusWindow)->controlList);
  4302.                     KillSound();
  4303.                 } else
  4304.                     if ((event->what == keyDown) && (! IsModalWindow(window)))
  4305.                     {
  4306.                         AdjustMenus();                        //adjust items properly
  4307.                         DoMenuCommand(MenuKey(key));
  4308.                     }
  4309.             } else                                            //non-Command keys
  4310.                 if (window != nil)                            //if there’s a window
  4311.                     DoKeyDown(key, window);
  4312.             break;
  4313.  
  4314.         case activateEvt:                        //true for activate, false for deactivate
  4315.             DoActivate((WindowPtr)event->message, event->modifiers & activeFlag);
  4316.             break;
  4317.  
  4318.         case updateEvt:                            //call DoUpdate with the window to update
  4319.             DoUpdate((WindowPtr)event->message);
  4320.             break;
  4321.  
  4322.         case diskEvt:                                //Call DIBadMount in response to a diskEvt
  4323.             if (HighWord(event->message) != noErr) {
  4324.                 where.v = kRecordTop;
  4325.                 where.h = kRecordLeft;
  4326.                 err = DIBadMount(where, event->message);
  4327.             }
  4328.             break;
  4329.  
  4330.         case osEvt:
  4331.             switch (event->message >> 24) {                    //get high byte of message
  4332.  
  4333.                 case suspendResumeMessage:
  4334.                     if ((event->message & suspendResumeMessage) != 0)
  4335.                         gInBackground = false;                //it was a resume event
  4336.                     else {
  4337.                         gInBackground = true;                //it was a suspend event
  4338.                         if (GetSoundMgrVersion() == 1)
  4339.                             KillSound();                    //stop any sound
  4340.                         window = FrontWindow();                //get front window
  4341.                         if (window != nil)                     //don’t use a nil window
  4342.                             HiliteWindow(window, false);    //then properly activate it
  4343.                     }
  4344.                     DoActivate(FrontWindow(), ! gInBackground);
  4345.                     break; //suspendResumeMessage
  4346.             }
  4347.             break; //osEvt
  4348.  
  4349.         case kHighLevelEvent:
  4350.             AEProcessAppleEvent(event);
  4351.             break;
  4352.  
  4353.     } //switch (event->what)
  4354. }
  4355.  
  4356. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4357. /*
  4358. Change the cursor’s shape, depending on its current position.  This also
  4359. calculates the region where the current cursor resides (for
  4360. WaitNextEvent).  This is based on its current position in global
  4361. coordinates.  If the mouse is ever outside of that region, an event is
  4362. generated causing this routine to be called again by the event loop.  This
  4363. allows me to change the region to where the mouse is currently located.
  4364. If there is more to the event than just “the mouse moved,” this gets
  4365. called before the event is processed to make sure the cursor is the right
  4366. one.  In any (ahem) event, this is called again before I fall back into
  4367. WaitNextEvent.  Extreme short values are used to create a wide open
  4368. region.  -SHRT_MAX - 1 is the largest negative short (-32768) and SHRT_MAX
  4369. is the largest positive short (32767).
  4370.  
  4371. BUG NOTE: The largest positive value for a region’s size is SHRT_MAX - 1
  4372. due to a very old bug that still remains to this day.
  4373. */
  4374.  
  4375. #pragma segment Main
  4376. void AdjustCursor(RgnHandle region)
  4377. {
  4378.     WindowPtr window;
  4379.     RgnHandle arrowRgn;
  4380.     RgnHandle sndCursorRgn;
  4381.     Rect sndCursorRect;
  4382.  
  4383.     window = FrontWindow();            //I only adjust the cursor when I am in front
  4384.     if ((! gInBackground) && (! IsDAWindow(window))) {
  4385.  
  4386.         arrowRgn = NewRgn();        //calculate regions for different cursor shapes
  4387.         sndCursorRgn = NewRgn();    //start with a big, big rectangular region
  4388.         SetRectRgn(arrowRgn, -SHRT_MAX - 1, -SHRT_MAX - 1, SHRT_MAX - 1, SHRT_MAX - 1);
  4389.  
  4390.         if (IsDocWindow(window)) {                //calculate region for document cursor
  4391.             sndCursorRect = window->portRect;
  4392.             SetPort(window);
  4393.  
  4394.             //make a global version of the viewRect
  4395.             LocalToGlobal(&TopLeft(sndCursorRect));
  4396.             LocalToGlobal(&BottomRight(sndCursorRect));
  4397.             RectRgn(sndCursorRgn, &sndCursorRect);
  4398.             SetOrigin(-window->portBits.bounds.left, -window->portBits.bounds.top);
  4399.             SectRgn(sndCursorRgn, window->visRgn, sndCursorRgn);
  4400.             SetOrigin(0, 0);
  4401.         }
  4402.  
  4403.         DiffRgn(arrowRgn, sndCursorRgn, arrowRgn);    //subtract other region
  4404.         if (PtInRgn(GetGlobalMouse(), sndCursorRgn)) {
  4405.             SetCursor(*(GetCursor(rSndCursor)));     //change cursor and region
  4406.             CopyRgn(sndCursorRgn, region);
  4407.         } else {
  4408.             SetCursor(&qd.arrow);
  4409.             CopyRgn(arrowRgn, region);
  4410.         }
  4411.         DisposeRgn(arrowRgn);                        //get rid of our local regions
  4412.         DisposeRgn(sndCursorRgn);
  4413.     }
  4414. }
  4415.  
  4416. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4417. /*
  4418. Get events forever, and handle them by calling DoEvent.  Since this
  4419. application requires System 6.0x or later I know that _WaitNextEvent is
  4420. always there, even without MultiFinder.  MultiFinder’s sleep is used to
  4421. determine how often I want to receive events, regardless if an event has
  4422. actually occurred.  In this application, I don’t perform any background
  4423. processing so I’m being super friendly by using LONG_MAX as a sleep
  4424. value.  This also helps keep Virtual Memory from paging me in just to run
  4425. my event loop and find out that nothing happened.  The application will
  4426. only be called upon for events that must be handled.  Also call
  4427. AdjustCursor each time through the loop.  AdjustCursor will return the
  4428. current region containing the mouse and is passed to WaitNextEvent.  If
  4429. the mouse travels out of the region, another event is generated.  I have
  4430. to call AdjustCursor just before doing the event to make sure the right
  4431. cursor is shown.  Another thing, if I have a sound playing asynchronously
  4432. then I want to dispose of my channel as soon as possible.  I set up a flag
  4433. in the SoundUnit that will keep track of when it has a channel allocated.
  4434. I can call the HasChannelOpen() function to find out if this is true.  It
  4435. pretty much like keeping track of when you’re in the background.  If a
  4436. channel is open, then the MultiFinder sleep time is adjusted to a
  4437. reasonable time that will allow me to catch when the sound has completed
  4438. so that I may dispose of my channels and status window.  That’s when I
  4439. return kPollingSleepTime.
  4440.  
  4441. VERSION 1.1: No longer putting the SANELib into a seperate segment, which then
  4442. needed to be unloaded.  Instead, I merge it into the Main segment.  Refer
  4443. to the Make file for further information.
  4444.  
  4445. VERSION 1.2: No longer using the SANELib at all. All of the SANE calls
  4446. are inline, and do not need a library to be linked in.
  4447. */
  4448.  
  4449. #pragma segment Main
  4450. void EventLoop(void)
  4451. {
  4452.     RgnHandle cursorRgn;
  4453.     EventRecord event;
  4454.     long sleep;
  4455.  
  4456.     cursorRgn = NewRgn();                    //1st time pass WNE an empty region
  4457.     while (!gTerminate) {
  4458.         if (HasChannelOpen())                //if we’re playing a sound
  4459.             sleep = kPollingSleepTime;        //use the polling sleep value
  4460.         else {
  4461.             sleep = LONG_MAX;                //default value for sleep
  4462.             UnloadSeg(_SoundUnit);            //unload the Sound Unit
  4463.         }
  4464.         UnloadSeg(OpenSoundDoc);            //unload the open code
  4465.         if (HasSoundCompleted())
  4466.             KillSound();
  4467.         if (LowOnReserve())
  4468.             RecoverReserve();
  4469.         AdjustCursor(cursorRgn);            //get the right cursor
  4470.         if (WaitNextEvent(everyEvent, &event, sleep, cursorRgn)) {
  4471.             AdjustCursor(cursorRgn);        //get the right cursor
  4472.             DoEvent(&event);
  4473.         }
  4474.     };                                        //loop forever; I quit through Terminate
  4475. }
  4476.  
  4477. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4478. /*
  4479. Set up the whole world.  Initialize global variables, Toolbox managers,
  4480. and menus.  If a failure occurs here, I will consider that the application
  4481. is in such bad shape that I should just exit.  Your error handling may
  4482. differ, but the checks should still be made.  I ask for a set of master
  4483. pointer blocks and all permanent storage at this point to cut down on
  4484. memory fragmentation.  I may be opening large numbers of resources and
  4485. documents so I allocate some extra master pointer blocks at the start.
  4486.  
  4487. VERSION 1.1:  Now supports opening of documents from the Finder.
  4488. */
  4489.  
  4490. #pragma segment Initialize
  4491. void Initialize(void)
  4492. {
  4493. #define kBroughtToFront    3
  4494.  
  4495.     EventRecord event;
  4496.     Handle menuBar;
  4497.     long response;
  4498.     short count;
  4499.     OSErr ignoreErr;
  4500.     Boolean ignoreResult;
  4501.  
  4502.     gTerminate = false;
  4503.     gInBackground = false;                        //we’ll be in the foreground soon
  4504.     gAppResRef = CurResFile();                    //save the resRef to myself
  4505.     for (count = 1; count <= kNumberOfMasters; count++)    //allocate master pointer blocks
  4506.         MoreMasters();
  4507.     InitGraf(&qd.thePort);                        //init managers, yawn...
  4508.     InitFonts();
  4509.     InitWindows();
  4510.     InitMenus();
  4511.     TEInit();
  4512.     InitDialogs(nil);
  4513.     InitCursor();
  4514.  
  4515. /*
  4516. ErrorSound is used to prevent the Dialog Manager from calling _SysBeep.
  4517. If I get a memory or resource Manager error it wouldn’t be the best
  4518. of plans to call _SysBeep which will want to allocate memory and load
  4519. a few resources.  Which could be bad if I just gave an Alert signalling
  4520. an out of memory condition. You only have to install this for Sound Manager
  4521. version  1 which is pretty buggy.
  4522.  
  4523. VERSION 1.2: Since we're using Sound Manager 2 or later, we don't have to
  4524. disable the multiple sampled sound channels demo and we don't need DoErrorSound.
  4525.  
  4526.     if (GetSoundMgrVersion() == 1)
  4527.     {
  4528.         ErrorSound(GetRoutineAddress(DoErrorSound));
  4529.         DisableItem(GetMenu(mDemos), iSampleSATB);
  4530.         DisableItem(GetMenu(mDemos), iSampleMelody);
  4531.     }
  4532. */
  4533.  
  4534. /*
  4535. This code is necessary to pull the application into the foreground.  I use
  4536. EventAvail because I don’t want to remove any events the user may have
  4537. done, such as typing ahead.  Until the application has made a few calls (3
  4538. seems to be the magic number) to the Event Manager, MultiFinder keeps me
  4539. in the background.   Splashscreens and Alerts will remain in a background
  4540. layer until we get a few events.  This is documented in Tech Note #180.
  4541. */
  4542.  
  4543.     for (count = 1; count <= kBroughtToFront; count++)
  4544.         ignoreResult = EventAvail(everyEvent, &event);
  4545.  
  4546. /*
  4547. Ignore the error returned from SysEnvirons; even if an error occurred,
  4548. the SysEnvirons glue will fill in the SysEnvRec. You can save a redundant
  4549. call to SysEnvirons by calling it after initializing AppleTalk.
  4550.  
  4551. VERSION 1.2: Using Gestalt and checking for System 7. Make sure you know if
  4552. the Gestalt trap is available before calling it. This code is compiled with the
  4553. SystemSevenOrLater flag on, when means you do not get the safe glue for Gestalt.
  4554. */
  4555.     if (! TrapExists(_Gestalt))
  4556.         EmergencyExit(sWrongVersion);
  4557.  
  4558.     if (Gestalt(gestaltSystemVersion, &response) != noErr)
  4559.         EmergencyExit(sStandardErr);
  4560.  
  4561.     if (response < 0x0700)
  4562.         EmergencyExit(sWrongVersion);
  4563.  
  4564. /*
  4565. Call the SoundUnit to initialize itslef.  If the SoundUnit encounters an error,
  4566. then it cannot be used and this means I’m leaving too.
  4567. */
  4568.  
  4569.     if (InitSoundUnit() != noErr)                //allocates 4 * 1064 bytes
  4570.         EmergencyExit(sInitSoundErr);
  4571.  
  4572. /*
  4573. Before I go any further, I want my reserve memory.  This is an emergency
  4574. reserve (sorta like my old VW had) when memory runs low.  If I cannot
  4575. obtain this reserve, then I’ll bail.  It’s also important to obtain my
  4576. reserve before testing if I have the desired amount of memory to run
  4577. this application.  Also, FailLowMemory will consider the memory reserve.
  4578. */
  4579.  
  4580.     if (! AllocateReserve())
  4581.         EmergencyExit(sLowMemory);
  4582.     SetGrowZone(GetRoutineAddress(MyGrowZone));
  4583.  
  4584.     menuBar = GetNewMBar(rMenuBar);                    //read menus into menu bar
  4585.     if (menuBar == nil)
  4586.         EmergencyExit(sNoMenus);                    //wow, how’d that happen?
  4587.     SetMenuBar(menuBar);                            //install menus
  4588.     DisposeHandle(menuBar);
  4589.     AppendResMenu(GetMenuHandle(mApple), 'DRVR');    //add DA names to Apple menu
  4590.     DrawMenuBar();
  4591.  
  4592.     InitStatusWindow();                                //get the status window ready
  4593.     //InitCursorCtl(nil);                                //MPW’s handy cursor routines
  4594.  
  4595. /*
  4596. Last, I want to make sure that enough memory is free for my application to
  4597. run.  It is possible that user may have adjusted the SIZE resource to too
  4598. small a setting or for some other reason the application started up in a
  4599. very small memory partition.  It’s also possible for a situation to arise
  4600. where the heap may have been of the requested size taken from the SIZE
  4601. resource, but a large scrap was loaded which left too little memory.  I
  4602. want to make sure that my free memory is not being modified by the scrap’s
  4603. presence.  So, I unload it to disk but if the application will run once
  4604. the scrap is unloaded, then you’ll probably not get it back into memory.
  4605. Thus losing the clipboard contents.  I preform this check after
  4606. initializing all the Toolbox and the basic features of this application,
  4607. such as showing the about box.
  4608. */
  4609.     if (FailLowMemory(kMinSpace)) {
  4610.         if (UnloadScrap() != noErr)
  4611.             EmergencyExit(sLowMemory);
  4612.         else {
  4613.             if (FailLowMemory(kMinSpace))
  4614.                 EmergencyExit(sLowMemory);
  4615.         }
  4616.     }
  4617.  
  4618. /*
  4619. Install the four core AppleEvent handlers.
  4620. */
  4621.     ignoreErr = AEInstallEventHandler(kCoreEventClass, kAEQuitApplication,
  4622.                 GetRoutineAddress(QuitApplicationEvent), 0, false);
  4623.  
  4624.     ignoreErr = AEInstallEventHandler(kCoreEventClass, kAEOpenDocuments,
  4625.                 GetRoutineAddress(OpenDocumentsEvent), 0, false);
  4626.  
  4627.     ignoreErr = AEInstallEventHandler(kCoreEventClass, kAEPrintDocuments,
  4628.                 GetRoutineAddress(PrintDocumentsEvent), 0, false);
  4629.  
  4630.     ignoreErr = AEInstallEventHandler(kCoreEventClass, kAEOpenApplication,
  4631.                  GetRoutineAddress(OpenApplicationEvent), 0, false);
  4632. }
  4633.  
  4634. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4635. /*
  4636. This routine is contained in the MPW runtime library.  It will be placed
  4637. into the code segment used to initialize the A5 globals.  This external
  4638. reference to it is done so that we can unload that segment, named %A5Init.
  4639. */
  4640.  
  4641. #ifdef applec
  4642. extern void _DataInit(void);
  4643. #endif
  4644.  
  4645. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4646. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MAIN PROGRAM ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4647. /*
  4648. If you have stack requirements that differ from the default, then you
  4649. could use SetApplLimit to increase StackSpace at this point, before
  4650. calling MaxApplZone.
  4651. */
  4652.  
  4653. #pragma segment Main
  4654. void main(void)
  4655. {
  4656. #ifdef applec
  4657.     UnloadSeg(_DataInit);            //note that _DataInit must not be in Main!
  4658. #endif
  4659.     MaxApplZone();                    //expand the heap so code segments load at the top
  4660.     Initialize();                    //initialize the program
  4661.     UnloadSeg(Initialize);            //note that Initialize must not be in Main!
  4662.     EventLoop();                    //call the main event loop
  4663.     ExitToShell();                    //we're out of here!
  4664. }
  4665. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MAIN PROGRAM ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4666. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4667.